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

太坑了

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

相关推荐
小猴子爱上树3 分钟前
跨境电商图片翻译工具,跨马批量处理视频字幕与抠图
python·音视频
smj2302_796826524 分钟前
解决leetcode第4033题有效K个不同元素子数组I
数据结构·python·算法·leetcode
Patrick在香港6 分钟前
Python asyncio vs 多线程 vs 多进程——同一份 HKOpenDataClient 实测 5/30/100 endpoint,谁是真的银弹
开发语言·python
Metaphor6929 分钟前
使用 Python 设置 Excel 文件属性
开发语言·python·excel
IT毕设实战小研25 分钟前
基于大数据的桂林热门旅游数据分析与可视化
大数据·python·机器学习·数据分析·django·课程设计·旅游
SamChan9029 分钟前
用PostgreSQL+pgvector构建PDF翻译记忆库:向量相似度检索+增量更新实战
数据库·python·ai·postgresql·pdf·wpf
金融小师妹30 分钟前
多因子市场推演:油价、英伟达与杰克逊霍尔如何影响资产定价的AI事件预测框架
人工智能·python·深度学习
大海变好AI36 分钟前
AI 工作流怎么搭建提升效率
大数据·人工智能·python
叫我:松哥36 分钟前
基于flask图书管理系统,技术栈flask+layui+sqlite+Echarts
后端·python·数据分析·flask·echarts·layui
落魄大学生之流水线上谋生计37 分钟前
Python Literal[] 类型提示详解
开发语言·python