[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()
相关推荐
跨境卫士-小汪38 分钟前
TikTokShop欧洲商品接口架构调整跨境技术团队需要做好哪些准备
大数据·人工智能·新媒体运营·跨境电商·跨境·营销策略
康小汪1 小时前
AI 写 Vue 总写成同一个味道:给它装 Skills,装的不是知识是边界
前端·vue.js·人工智能·ai编程·最佳实践
收放扳机2 小时前
多机连线(In-Line)场景下,收放板机“缓存工位”的容量与架构选型参考
人工智能·科技·自动化·制造·pcb工艺
武天旭2 小时前
AI安全--AI大模型的后门攻击检测与防御
人工智能·深度学习·安全·机器学习
智能运维指南2 小时前
研制过程“两张皮“怎么破:研制一体化支撑平台的定位、能力边界与落地前提
java·前端·人工智能·嘉为蓝鲸
人工智能AI技术2 小时前
DeepInfer开源炸场!别再妄想个人电脑跑满血DeepSeek
人工智能
深蓝电商API2 小时前
用AI生成拟人行为:让鼠标轨迹更“有人味”
人工智能·爬虫
znnnk2 小时前
数据库被AI“重写”:2026,从CPU中心走向GPU中心
数据库·人工智能·oracle
深蓝AI2 小时前
网站正在对 AI Agent 集体关门:亚马逊封锁 Muse、银行拒绝登录,开发者怎么活下去
人工智能
jason_renyu3 小时前
Vue 4 × AI:流式对话、Agent 状态与高性能渲染的下一代组合
人工智能·vue4·vue4和ai·vue4xai