[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()
相关推荐
六月的可乐几秒前
快速搭建 AI 客服系统:用 AI-Agent-Node + AISuspendedBallChat 打造可落地的智能客服方案
人工智能·gpt·ai·ai编程
szxinmai主板定制专家2 分钟前
基于ARM+FPGA高性能MPSOC 多轴伺服设计方案
arm开发·人工智能·嵌入式硬件·fpga开发·架构
fqrj20264 分钟前
网站建设公司怎么选?国内口碑网站建设公司推荐哪家?
大数据·人工智能·html·网站开发
minhuan6 分钟前
大模型对抗性训练:防御Prompt攻击与恶意生成生成攻击,提升模型安全性.153
人工智能·大模型对抗性训练·prompt安全机制·大模型应用安全
QQ676580086 分钟前
智慧工地要素识别数据集 塔吊挂钩识别数据集 吊物识别数据集 工地人员识别数据集 目标检测识别 工地识别数据集
人工智能·目标检测·目标跟踪·工地要素识别·塔吊挂钩·吊物识别·工地人员识别
AI服务老曹7 分钟前
[深度解析] 兼容 X86/ARM 与多模态 NPU:基于 GB28181/RTSP 的工业级 AI 视频中台架构设计
arm开发·人工智能·音视频
qcx238 分钟前
【AI Agent实战】零基础用 AI Agent 做电商调研:5 道题 + 6 份 Prompt,跑通一家 16 亿品牌的完整拆解
人工智能·chatgpt·prompt
IT_陈寒8 分钟前
React状态管理这个坑,我终于爬出来了
前端·人工智能·后端
Byron__9 分钟前
AI学习_04_向量概念
人工智能·学习
fzil00110 分钟前
GitHub 项目自动 Star + Issue 监控
人工智能·github·issue