[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()
相关推荐
tmlx3I0813 分钟前
高光谱拼接算法(六)RANSAC 误匹配剔除
人工智能·算法·机器学习
Mininglamp_271815 分钟前
Claude Code 封禁中国开发者之后:本地 AI 编程工具的替代方案实测
开发语言·人工智能·windows·开源软件·ai-native
硅谷秋水22 分钟前
World Engine:迈向自动驾驶的后训练时代
人工智能·深度学习·机器学习·计算机视觉·语言模型·自动驾驶
RobinDevNotes23 分钟前
PentAGI:全自主 AI 渗透测试代理系统
人工智能
明理的信封30 分钟前
AI 基础设施的“去 Python 化“:Rust 与 C# 的两条替代路径
人工智能·python·rust
Tiansan666642 分钟前
郑州AI问答推广公司:如何用AI提升转化率
人工智能·郑州ai问答推广公司
龙亘川44 分钟前
开源本地 AI 智能体网关 OpenClaw 深度实践:架构解析、全场景部署与自动化落地指南
人工智能·架构·开源·openclaw
霍格沃兹测试开发学社测试人社区1 小时前
为企业提供专业、灵活、高效的一体化测试支持
人工智能
xixixi777771 小时前
产业全景解读:太空算力、国产芯、国产大模型、6G 空天地、AI 可信身份、后量子安全多线全面突破
人工智能·安全·ai·大模型·数据中心·通信·运营商
恣逍信点1 小时前
主观是客观的聚焦
人工智能·学习·程序人生·生活·业界资讯·交友·哲学