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

太坑了

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

相关推荐
孤狼warrior24 分钟前
SCTR 五次失败的安全 BN 路由器
人工智能·python·深度学习·算法·安全·yolo
天赐范式29 分钟前
天赐范式第159天:让广播走出本机——HTTP通道发出第一声
python·broadcast·urllib·http.server·天赐范式·动态运行时·http通道
keke.shengfengpolang36 分钟前
2026秋招信用风险分析岗面试:SQL和Python到底要学到什么程度才能过?
python
lytao12337 分钟前
90% 覆盖率不等于没 Bug:用风险配置测试组合
前端·javascript·bug·软件工程
2601_962099081 小时前
python flask sqlalchemy连接数据库流程介绍
数据库·python·flask·教程·sqlalchemy
2601_962293241 小时前
python接口自动化(二十八)--html测试 报告——下(详解)
python·接口自动化·编码问题·htmltestrunner·报告优化
烂蜻蜓1 小时前
Flask入门教程(附录):模板渲染API——Jinja2集成全解析
后端·python·flask
2601_962387821 小时前
Python CUDA 编程 - 2 - Numba 简介
python·numpy·cuda·jit编译器·numba
Joker-Full-stack1 小时前
higress Grafana生产事故复盘:Loki 2.9 WAL 竞态 Bug 导致 5 天审计日志消失
bug·grafana·higress
承渊政道1 小时前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(实战训练自己的ChatGPT从续写模型到对齐助手:RLHF、奖励模型与PPO精读)
人工智能·pytorch·chatgpt·预训练·rlhf·大模型微调