[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()
相关推荐
byte轻骑兵4 分钟前
【BlueZ 】input 模块:蓝牙鼠标/键盘等输入设备的基础适配逻辑
linux·人工智能·bluez·电脑蓝牙·嵌入式蓝牙
autotian4 分钟前
神经网络及其应用
人工智能·深度学习·神经网络
雾屿_Mistisle6 分钟前
AI安全设计总结
人工智能·机器学习·数据分析
aichitang20247 分钟前
前端小skill
前端·人工智能·算法·ai·前端框架
来两个炸鸡腿16 分钟前
【Datawhale2609】算子开发实战 task02-TileLang Add 与 NineToothed Vector Add
人工智能·大模型·算子
Hotchip_MEMS16 分钟前
传统咪头与MEMS硅麦:雾化器气流传感方案对比
人工智能·笔记·物联网·电脑·制造
4SAPI22 分钟前
大模型接口管理平台推荐:多模型时代的API Gateway架构与选型分析
人工智能·agent
皇儒无上23 分钟前
智慧矿山-关于推进山西省煤矿灾害差异化智能化建设强化 AI 风险防控的政策建议
人工智能·机器学习·区块链
YOLO数据集集合28 分钟前
小目标无人机、飞机、直升机检测数据集 | 小目标检测 无人机检测 空中目标识别 低空安防 反无人机9090期
深度学习·yolo·目标检测·无人机·飞机·小目标·直升机
byte轻骑兵31 分钟前
【LE Audio】PBP精讲[4]: 公共广播通告的设计逻辑与数据交互流程
人工智能·音视频·le audio·低功耗蓝牙音频