[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()
相关推荐
我的青春不太冷15 分钟前
【探索篇】探索部署离线AI在Android的实际体验
android·人工智能·经验分享·科技·架构
MYT_flyflyfly23 分钟前
计算机视觉-边缘检测
人工智能·计算机视觉
破晓之翼1 小时前
司库建设-融资需求分析与计划制定
大数据·人工智能·信息可视化
冰糖小新新1 小时前
ELF2开发板(飞凌嵌入式)搭建深度学习环境部署(RKNN环境部署)
人工智能·深度学习
MichaelIp2 小时前
大模型高级工程师实践 - 将课程内容转为音频
人工智能·gpt·ai·语言模型·自然语言处理·aigc·音视频
慕容木木2 小时前
本地部署最强人工智能服务:方案(一)Chatbox+硅基流动(满血DeepSeek R1)
人工智能·华为云·deepseek·硅基流动·chatbox
弥树子2 小时前
使用 PaddlePaddle 实现逻辑回归:从训练到模型保存与加载
人工智能·逻辑回归·paddlepaddle
倔强的石头1063 小时前
DeepSeek横空出世,AI格局或将改写?
人工智能·aigc
Anlici3 小时前
强势DeepSeek——三种使用方式+推理询问指令😋
前端·人工智能·架构
MichaelIp4 小时前
大模型高级工程师实践 - 将课程内容转为视频
人工智能·python·自然语言处理·langchain·prompt·aigc·音视频