[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()
相关推荐
rgb2gray1 分钟前
AI 的“诚实”指南:一文详解 Conformal Prediction (共形预测) 与 Split Conformal
人工智能·python·机器学习·数据分析·可解释·共性预测·一致性预测
Agilex松灵机器人14 分钟前
持续更新|从零到玩转Moveit机械臂控制(一)
人工智能·python·机器人·学习方法
Coder_Boy_20 分钟前
基于SpringAI的在线考试系统-试卷管理与考试管理模块联合回归测试文档
人工智能·spring boot·架构·领域驱动
子午31 分钟前
【2026原创】卫星遥感图像识别系统+Python+深度学习+人工智能+算法模型+TensorFlow
人工智能·python·深度学习
_ziva_31 分钟前
大模型分词算法全解析:BPE、WordPiece、SentencePiece 实战对比
人工智能·深度学习·自然语言处理
光锥智能36 分钟前
飞书钉钉AI硬件争夺战:录音背后的入口之争
人工智能·钉钉·飞书
跨境小渊39 分钟前
DeepBI Listing优化功能第一弹:对标竞品评分报告
人工智能
xixixi777771 小时前
解析 Claude模型 —— Anthropic公司打造,以安全性和推理能力为核心竞争力的顶尖大语言模型
人工智能·ai·语言模型·自然语言处理·大模型·claude·主流模型
大唐荣华1 小时前
机器人落地“首台套”补贴,到底指什么?
人工智能·机器人