[Bert] 提取特征之后训练模型报梯度图错误

报错:

RuntimeError: stack(): functions with out=... arguments don't support automatic differentiation, but one of the arguments requires grad.

或者

RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.

原因:

训练模型的时候,输入数据x,y不应该requires_grad,而bert模型输出的embeddings默认是requires_grad的,所以会报错。

解决方法:

提取完embeddings之后,使用 embeddings.detach() 解除绑定就行了。

最后的代码:

复制代码
from transformers import BertTokenizer, BertModel

class BertFeatureExtractor:
    def __init__(self):
        self.tokenizer = BertTokenizer.from_pretrained('bert-base-chinese')
        self.model = BertModel.from_pretrained('bert-base-chinese')

    def extract_features(self, text: str):
        inputs = self.tokenizer(text, return_tensors="pt")
        if len(inputs["input_ids"]) > 512:
            inputs["input_ids"] = inputs["input_ids"][:512]
            inputs["attention_mask"] = inputs["attention_mask"][:512]
        outputs = self.model(**inputs)
        return outputs.last_hidden_state[:,0,:]
    
feat = feat.detach()
相关推荐
starzy19905 小时前
深入理解Scala隐式类:扩展方法机制
开发语言·人工智能·scala
深蓝AI5 小时前
为什么 agent 的 demo 都很惊艳,上了生产就不靠谱
人工智能·程序员
数字新视界5 小时前
信创动环监控在机房环境管理中的智能化应用与实践分析
大数据·人工智能·物联网·信息与通信·动环监控系统
岁月宁静6 小时前
DeepSeek Harness 实战与架构解析:让 Agent 从“会聊”到“能交付”
人工智能·python·agent
深蓝AI6 小时前
一个项目五个 AI 同时干活,Claude Code 怎么让它们不互相打架
人工智能·程序员
forest_096 小时前
多 Agent 协作第二课:交叉验证≠独立验证
人工智能·python·算法·机器学习·prompt·agi
ZONGYUAN-ROOT7 小时前
【工具治理】Nginx换机丢16子域事故复盘
人工智能
dozenyaoyida7 小时前
AI与大模型新闻日报 | 2026-11-08
人工智能·搜索引擎·ai·大模型·新闻
泯泷7 小时前
AI Agent 工具设计:读完一百页 PDF,不等于真的看懂了
人工智能·llm·agent
泯泷9 小时前
AI 怎样"查资料"?——RAG 检索增强生成入门(三)
人工智能·llm