[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()
相关推荐
智购科技无人售货机工厂1 分钟前
2026自动售货机云端API设计规范:从RESTful到GraphQL的接口演进~YH
android·人工智能·驱动开发·单片机·云原生·pandas·设计规范
安托智造6 分钟前
2026高端装备行业数智化交流会回顾:工业AI、虚拟孪生与3DE正向研发闭环如何落地
人工智能·plm·工业ai·3dexperience平台
doitnow20006 分钟前
淘宝开店教程收费前要确认哪些项目?
大数据·人工智能
克里斯蒂亚诺更新8 分钟前
图像识别的两种解决方案——使用深度学习
人工智能·深度学习
龙亘川17 分钟前
免费开源丨统一决策分析系统 综合态势功能的实现机理与技术难度
人工智能·信息可视化·开源·智慧城市·#后台开发
2601_9623004718 分钟前
Python TensorFlow对比PyTorch_Python TensorFlow和PyTorch在机器学习中的差异
pytorch·python·深度学习·机器学习·tensorflow
TaoMetrix1 小时前
Microduck 爆火之后:TaoMetrix 如何帮助品牌抓住 AI 陪伴机器人新机会
人工智能·机器人
来让爷抱一个2 小时前
2026 结构化输出:把Schema写进SPEC,MonkeyCode 云端跑通
人工智能·机器学习
霸道流氓气质3 小时前
Spring AI异常处理与重试机制
java·人工智能·spring
在所不辞兄3 小时前
【零基础学智能仿真-07】随机森林——用多棵树获得更稳定的力学预测
人工智能·深度学习·神经网络·机器学习·工程技术