[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()
相关推荐
Zero_to_zero123414 分钟前
Claude code系列(一):claude安装、入门及基础操作指令
人工智能·python
szcsun514 分钟前
机器学习(二)-线性回归实战
人工智能·机器学习·线性回归
Yeats_Liao15 分钟前
异步推理架构:CPU-NPU流水线设计与并发效率提升
python·深度学习·神经网络·架构·开源
普通网友17 分钟前
Android16 adb投屏工具Scrcpy介绍。
人工智能
搬砖者(视觉算法工程师)19 分钟前
语义分割:基于 TensorFlow 对 FCN 与迁移学习的探究
人工智能
cookqq28 分钟前
基于Spring AI+本地大模型+MongoDB实现私密化与记忆能力-企业级免费大模型应用
人工智能·mongodb·spring
云卓SKYDROID34 分钟前
无人机飞行模式详解
人工智能·无人机·高科技·云卓科技·技术解析、
哥布林学者38 分钟前
吴恩达深度学习课程五:自然语言处理 第三周:序列模型与注意力机制(一)seq2seq 模型
深度学习·ai
数字游民95271 小时前
小程序上新,猜对了么更新110组素材
人工智能·ai·小程序·ai绘画·自媒体·数字游民9527
泰迪智能科技1 小时前
分享|联合编写教材入选第二批“十四五”职业教育国家规划教材名单
大数据·人工智能