[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()
相关推荐
chh5635 小时前
从 BERT 到大模型:让模型从“会接龙”到“会回答
人工智能·深度学习·bert
TomEval5 小时前
【测AI】第26篇:线上模型监控与告警体系 — 测试不是终点
人工智能·python·功能测试·ai
ZhengEnCi6 小时前
AI 总模仿代码库里的过时写法怎么办:先清坏样例,再用类型与测试让 AI 无法犯错
人工智能·ai编程
一只爱撸猫的程序猿6 小时前
五周、两个开源仓库、九次拦截之后:AI 时代程序员缺的到底是什么
人工智能·后端·开源
GitCode官方6 小时前
开源鸿蒙跨平台直播|AI 时代,用 cj-tauri 开发鸿蒙 PC 应用
人工智能·华为·harmonyos·atomgit
老金带你玩AI7 小时前
GPT-6.2更强更便宜了,为什么还有人骂?
人工智能
CyrusYiVPP7 小时前
实测 uv 0.13.7:同一套包,pip 装 94 秒,它只用 19 秒
人工智能·python
泯泷7 小时前
OpenClaw 退潮背后,是 AI 圈“技术自嗨”的终结
人工智能·chatgpt·llm
罗西的思考7 小时前
【轻量化复刻大模型 / KIMI K3】Muon 优化器及 训练系统
人工智能·算法·机器学习
屿华AI8 小时前
AUTOSAR 实战-诊断工具 | 用 Claude Code 开发诊断测试工具:AI 协作开发实践
人工智能·测试工具