[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()
相关推荐
知几蜗牛3 小时前
蛋白预测快2.9倍,科学AI最难的是让整条流水线不空转
人工智能
蓝速科技3 小时前
企业展厅数字人导览效果提升与选型实战指南丨蓝速科技
大数据·运维·数据库·人工智能·科技·microsoft
2601_962304253 小时前
零门槛上手AI短片首尾帧制作完整短片?
人工智能
AI人工智能集结号3 小时前
第一次品牌AI检测,怎样发现最值得继续观察的问题?
人工智能
码农学院3 小时前
零售电商GEO踩坑复盘:把 MySQL 商品库自动映射成 Product Schema 的完整方案
人工智能·mysql·零售·geo
大江东去浪淘尽千古风流人物3 小时前
【LoMa】局部特征匹配重访:从LoMa-B到旋转不变LoMa-R的架构与工程实践
开发语言·深度学习·计算机视觉·r语言·视觉定位·sfm·局部特征匹配
AI深栈3 小时前
第 8 章 · Tool Calling 与 Tool Search
java·人工智能
陈天伟教授3 小时前
具身数据采集黑话(4)
人工智能·windows·具身智能
用户5274675614213 小时前
别让 AI 从聊天记录直接写稿:先建一个有证据边界的选题队列
人工智能
秦先生在广东3 小时前
Harness CLI 3.0:终端原生的统一代码审查与 CI/CD 命令行工具
人工智能