[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()
相关推荐
MacroZheng几秒前
面试官:“你连Claude Code都没用过吗?”,我怼回去:“就没用过又怎么了?”
人工智能·后端·claude
IDZSY04301 分钟前
【技术视角】从0到1拆解机乎AI:AI社交平台的技术架构与产品设计
人工智能
视觉&物联智能2 分钟前
【杂谈】-人工智能于现代网络安全运营的价值持续攀升
人工智能·安全·web安全·ai·chatgpt·agi·deepseek
昨夜见军贴06163 分钟前
采购订单校验报告审核效率革命,IACheck与AI报告审核全力赋能无误处理
人工智能
数据牧羊人的成长笔记6 分钟前
认识深度学习_PyTorch入门+神经网络基础+卷积神经网络+迁移学习+生成对抗网络_GAN+CNN目标检测+循环神经网络与NLP
pytorch·深度学习·神经网络
optimistic_chen8 分钟前
【AI Agent 全栈开发】提示词技巧(prompt)
java·人工智能·ai·prompt·agent
暗夜猎手-大魔王8 分钟前
转载--AI Agent 架构设计:多 Agent 协作(OpenClaw、Claude Code、Hermes Agent 对比)
人工智能
chatexcel11 分钟前
专业报告PPT自动生成教程:基于元空AI的文档解析与智能排版实践
人工智能·powerpoint
海兰12 分钟前
【第21篇】 Chat Memory Example
人工智能·spring ai
Alex艾力的IT数字空间14 分钟前
大模型的“Think 模式”(思考模式)关闭的配置方式
人工智能·机器人·web3·github·开源软件·量子计算·开源协议