[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()
相关推荐
ZzT2 小时前
怎么做才不会被 AI 替代?
人工智能·程序员
道友可好2 小时前
从今天开始:你的第一个 Harness Engineering 实践
前端·人工智能·后端
小姜前线技术3 小时前
AI回答代码块高亮加一键复制
人工智能
洛阳泰山3 小时前
从 0 到 1.6K Star:一个 Java 开源项目的增长复盘
人工智能·后端·开源
米小虾4 小时前
Agent Skill 设计模式完全指南
人工智能·agent
饼干哥哥4 小时前
保姆级教程:用Image2 + Seedance2.0 做长视频,以品牌广告为例
人工智能
米小虾5 小时前
Agent Skill 规范与 Skill-Creator 核心思想
人工智能·agent
ZhengEnCi5 小时前
09e-斯坦福CS336作业四:大规模语言模型训练数据收集与处理
人工智能
oil欧哟5 小时前
Codex 最佳实践(超级长文):先搞懂 AI,再用好 AI
前端·人工智能·后端
甲维斯5 小时前
日本发布比肩Fable5的模型?Fugu Ultra初探!
人工智能·ai编程