[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()
相关推荐
自律懒人3 分钟前
AI Agent 记忆方案横评:Memoria vs OpenClaw vs MCP,让Agent记住你的3种方式
人工智能·大模型·ai编程
Allen正心正念20253 分钟前
AI编程—claude code中plugin三种范围模式的配置方法
人工智能·ai编程
豆豆4 分钟前
2026实测:AI生成UI设计稿后,如何优雅集成到PageAdmin CMS?(附标签替换代码)
人工智能·ui·cms·建站系统·ai工具·ai建站
梦想三三4 分钟前
【NLP入门到实战】TF-IDF算法详解 + 红楼梦120回关键词提取
人工智能·python·计算机视觉
优信其乐7 分钟前
AI数字人讲解视频的未来,不是数字人,而是PPT
人工智能·powerpoint·yoco·ppt转视频工具
雪隐8 分钟前
AI股票小助手03-Tushare数据采集
人工智能·后端
小烤箱8 分钟前
什么是 ROS2:机器人软件的数据加工工业园区
人工智能·机器人·ros
2601_955767428 分钟前
观复盾护景贴:东方哲思与双护科技的深度实测
人工智能·科技·ios·iphone·圆偏振光·磁控溅射
lpd_lt8 分钟前
服务端类vue等页面AI测试方向
前端·vue.js·人工智能
黄啊码10 分钟前
【黄啊码】AI提速后,我睡得更晚了
人工智能