[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()
相关推荐
jikemaoshiyanshi3 小时前
AWS 中国峰会 2026 有哪些 AI Agent 相关演讲可以看?按业务、研发与生产阶段选看
大数据·人工智能
网易易盾4 小时前
AI互动产品安全合规体系架构:制度/技术/运营/证据四层落地
人工智能·安全·aigc·内容安全
新知图书4 小时前
4.3 链接速读
人工智能·语音识别·ai助手·千问
江苏久众新视4 小时前
SOP-AI实战:基于AI视觉与视频检测,精准管控空调管件装配防漏防错
人工智能
u0103055275 小时前
Java AWT鼠标事件全解析
人工智能·1024程序员节
tuanxiang6 小时前
中英文AI检测的跨语系误判问题排查与修复
人工智能
冬奇Lab6 小时前
开源项目第178期:OptMem — 426 个 token 的提示词,给 AI Agent 跨会话的持久记忆
人工智能·开源·资讯
冬奇Lab6 小时前
代码库知识库系列(09):用 codebase-memory-mcp 实战——在 LightRAG 上跑三路召回
人工智能
科技圈观察7 小时前
选哪家服务商做跨境业务KYC数字身份认证和合规支持?2026出海选型参考
大数据·人工智能