[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()
相关推荐
彭军辉几秒前
生命体AI和数字生命有什么区别
人工智能
Rauser Mack7 分钟前
AI大模型测评:GPT-5.5翻车、Claude封神——大模型选型的真相
人工智能·gpt·prompt
2601_9619460823 分钟前
AI API 网关实战:从单 Key 管理到企业级多租户架构
大数据·人工智能·金融·架构·api·个人开发
AI-好学者24 分钟前
GraphRAG与混合检索架构
人工智能·知识图谱
智写-AI1 小时前
真实有效的免费降英文AI工具服务商
人工智能·python
大鹏的NLP博客1 小时前
深度学习模型部署一致性验证规范
人工智能·深度学习
土星云SaturnCloud1 小时前
边缘计算驱动绿氢生产过程智能寻优:电解槽级实时优化技术解析
服务器·人工智能·ai·边缘计算
Urbano2 小时前
校服精细化缝制难点、全流程自动化改造方案与核心贴袋设备选型实操科普
人工智能
IT_陈寒2 小时前
SpringBoot自动配置失灵?你可能忘了这个关键注解
前端·人工智能·后端