[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()
相关推荐
霸道流氓气质6 分钟前
Spring AI Ollama 连接超时问题排查与解决:OkHttp 读超时配置全指南
人工智能·spring·okhttp
道友可好10 分钟前
Spec Kit:GitHub 官方出品,规范即代码
前端·人工智能·后端
weixin_5051544618 分钟前
打通工业安全治理“最后一公分”:Bowell 发布 Runtime 治理平台
大数据·人工智能·安全·3d·数字孪生·数据可视化
烬、、、22 分钟前
如何用 Claude Code 调用 gpt-image2 生成图片?
人工智能·笔记·gpt·prompt·skills
郑州光合科技余经理23 分钟前
海外版外卖系统:如何快速搭建国际化外卖平台
java·开发语言·前端·人工智能·小程序·系统架构·php
王哈哈^_^25 分钟前
YOLO分类任务训练教程:从数据准备到模型部署全流程
人工智能·yolo·计算机视觉·分类·数据挖掘
下午写HelloWorld28 分钟前
同态加密(Homomorphic Encryption, HE)
人工智能·算法·密码学·同态加密
Kobebryant-Manba28 分钟前
安装cuda
pytorch·python·深度学习·conda·numpy
尚可签28 分钟前
小烟改写工具:让文字表达更自然,让文档改写更高效
人工智能
小何code28 分钟前
【Python零基础入门】第10篇:Python列表方法与应用实例
数据库·人工智能·python