[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()
相关推荐
码云数智-大飞14 分钟前
小程序制作平台有哪些?SaaS小程序制作平台对比评测
大数据·人工智能
新缸中之脑1 小时前
Arduino AI手势识别系统
人工智能
码农小韩1 小时前
AIAgent应用开发——DeepSeek分析(二)
人工智能·python·深度学习·agent·强化学习·deepseek
ctrigger1 小时前
家和万事兴
大数据·人工智能·生活
Bill Adams1 小时前
深度解析 WebMCP:让网页成为 AI 智能体的工具库
人工智能·智能体·mcp
新缸中之脑1 小时前
StrongDM:软件黑灯工厂
人工智能
冰西瓜6001 小时前
深度学习的数学原理(八)—— 过拟合与正则化
人工智能·深度学习
Christo31 小时前
windows系统配置openclaw
人工智能·机器学习
小李独爱秋1 小时前
机器学习与深度学习实验项目3 卷积神经网络实现图片分类
人工智能·深度学习·机器学习·分类·cnn·mindspore·模式识别
爱问问题的小李1 小时前
AI生成的Threejs常用Api学习计划
人工智能·学习