[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()
相关推荐
LYFlied1 小时前
EVMbench解读:AI Agent如何检测、修复并利用智能合约漏洞
人工智能·网络安全·openai·智能合约·ai agent·evm·智能合约区块链
犀利豆1 小时前
AI in Harness(二)
java·人工智能·后端
IT_陈寒1 小时前
Python装饰器竟然偷偷改了函数名?这个坑我爬了三天
前端·人工智能·后端
阿里云大数据AI技术1 小时前
DataWorks Data Agent “又双叒叕”升级:更低成本、更强智能、更多连接
人工智能·agent
Elastic 中国社区官方博客2 小时前
Elastic 在 Everest Group 企业搜索产品 PEAK Matrix® 评估 2026 中被评为领导者
大数据·运维·人工智能·elasticsearch·搜索引擎·ai·全文检索
牧艺2 小时前
Cursor 多 Agent 与 Worktree:大重构不再赌一把
人工智能·agent·cursor
一键生成网站2 小时前
开源AI政务大屏制作工具对比:国产化安全合规选型深度分析
人工智能·开源·政务·
智食分子2 小时前
大模型开发框架LangChain
人工智能
YHL2 小时前
🤖 Agent 智能体开发实战 · 第一课:Tool Use —— 让大模型自动干活
前端·javascript·人工智能
萧萧秦风瘦飞马2 小时前
CSDN博客-第6天-DataLoader与二维非线性分类
人工智能·分类·数据挖掘