[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()
相关推荐
skywalk8163几秒前
Kotti Next:使用FastAPI+Vue 3构建的现代无头CMS-Kotti CMS的精神继承者(使用WorkBuddy AI自动编程)
前端·vue.js·人工智能·fastapi·kotti
aircrushin2 分钟前
三月AI十件大事盘点
人工智能
CDA数据分析师干货分享3 分钟前
统计学本科生CDA数据分析师二级备考经验分享
大数据·人工智能·经验分享·数据分析·cda证书·cda数据分析师
Cosolar1 小时前
RAG(检索增强生成)面试指南
人工智能·aigc·openai
90后的晨仔1 小时前
MP4 转 GIF 完整技术指南:从原理到实践
人工智能
新缸中之脑2 小时前
Google Stitch 产品设计实测
人工智能
Slow菜鸟8 小时前
AI学习篇(三) | AI效率工具指南(2026年)
人工智能·学习
北京软秦科技有限公司9 小时前
AI审核如何助力合规取证?IACheck打造环境检测报告电子存证与法律风险防控新路径
大数据·人工智能
qq_359716239 小时前
openpi使用过程中相关问题
人工智能·深度学习·机器学习
minhuan9 小时前
医疗AI智能体:从数据到关怀人文设计:告别冰冷精准,构建有温度的诊疗交互.131
人工智能·ai智能体·智能体的人文设计·医疗ai人文设计·构建医疗ai智能体