[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()
相关推荐
双翌视觉几秒前
影像测量仪中工件反光/深色表面测量不准怎么办?
人工智能·opencv·计算机视觉·影像测量仪
打工仔折腾 AI12 分钟前
C++ AI SDK(十):DataManager的数据库读写、事务与一致性设计
开发语言·数据库·c++·人工智能·后端·python·性能优化
林墨聊AIGC12 分钟前
AI首尾帧一键生成连贯视频
大数据·人工智能·科技·ai作画·aigc·音视频
ONLYOFFICE14 分钟前
怎么用DeepSeek处理日常文档工作?直接在编辑界面使用,无需跳转!
人工智能·onlyoffice·deepseek
Forget the Dream18 分钟前
Spring AI 2.0 系列(四):Starter 与 OpenAI-compatible:一个不绑死厂商的模型环境
java·人工智能·spring·springai
king135987455037 分钟前
Clipstral 视频语义检索:FFmpeg PTS 验证、向量索引与端侧部署
人工智能·ffmpeg·音视频·大语言模型·llama·本地部署·llama.cpp
鬼手点金38 分钟前
事件驱动的异步 Agent
人工智能·安全·机器学习·缓存·prompt
_小许_42 分钟前
RNN 是怎么“读”文本的:从字符到隐藏状态,手写一个字符级语言模型
人工智能·rnn·语言模型
圆心角43 分钟前
AI 没有抢走你的工作,它拆了你的训练场
前端·人工智能·ai编程