[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()
相关推荐
qq_3751679811 分钟前
No module named ‘mmcv._ext‘
人工智能·计算机视觉
JoengGaap12 分钟前
智能体学习(定义、框架、简单实现搭建)
人工智能
love530love32 分钟前
Windows 11 下再次成功本地编译 Flash-Attention 2.8.3 并生成自定义 Wheel(RTX 3090 sm_86 专属版)
人工智能·windows·笔记·编译·flash_attn·flash-attn·flash-attention
模型启动机33 分钟前
港大联合字节跳动提出JoVA:一种基于联合自注意力的视频-音频联合生成模型
人工智能·ai·大模型
无心水36 分钟前
【神经风格迁移:全链路压测】29、AI服务压测实战:构建全链路压测体系与高并发JMeter脚本设计
人工智能·高并发·混沌工程·全链路压测·ai镜像开发·ai镜像·神经风格
怪我冷i1 小时前
Zed编辑器安装与使用Agent Servers(腾讯CodeBuddy、阿里百炼Qwen Code、DeepSeek Cli)
人工智能·编辑器·ai编程·ai写作·zed
AI_Auto1 小时前
智能制造-AI质检六大场景
人工智能·制造
特立独行的猫a2 小时前
AI工具推荐:Google 神秘武器 CodeWiki ---上古项目的终极克星
人工智能
nn在炼金2 小时前
大模型领域负载均衡技术
人工智能·算法·负载均衡
久菜盒子工作室2 小时前
【A股复盘】2025.12.30
人工智能·经验分享·金融