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

太坑了。

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

相关推荐
最强小杰40 分钟前
DeepSeek V4 Flash + Codex CLI 接入教程:原生 Responses API 适配,从配置到跑通收藏这篇就够了(2026)
java·前端·python·ai
DeepVisionary1 小时前
为拿并网许可,OpenAI在佐治亚新园区同意高峰期断电三成
python·自动化
VIP_CQCRE2 小时前
内容自动化越跑越乱?先补上状态、去重和失败恢复
python·ai·工作流·幂等设计·内容自动化
我喜欢就喜欢2 小时前
RAG 重排序 Rerank 实战:用 bge-reranker 把 Top-K 命中率拉回来
python·大模型·向量检索·rag·rerank
专注仿真2 小时前
卷积神经网络(CNN)算法详解
人工智能·python·算法·代码·大模型训练
isfox2 小时前
Python3 协程:异步编程的核心机制与实战
python
NJPJI_Yang2 小时前
鸿蒙 HarmonyOS 7 应用内存优化:appMemoryOptimizer 释放 so 页缓存实战
pytorch·深度学习·harmonyos
用户298698530143 小时前
Python 将 Markdown 批量转为 HTML:单文件与目录遍历两种实现
python·html·markdown
miofly3 小时前
GitHub 今日推荐|auto-ontology:给 Agent 装上企业数据的语义索引
python·开源·github