[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()
相关推荐
WJSKad123510 分钟前
基于改进YOLO11的超市商品与电子设备多类别目标检测方法C3k2-ConvAttn
人工智能·目标检测·计算机视觉
wangmengxxw24 分钟前
SpringAi-mcp高德
人工智能·高德·springai·mcp
丝瓜蛋汤30 分钟前
Proof of the contraction mapping theorem
人工智能·算法
觉醒大王34 分钟前
如何整理文献阅读笔记? (精读与泛读)
前端·css·笔记·深度学习·自然语言处理·html·学习方法
renhongxia138 分钟前
数字孪生国内外发展现状,数字孪生技术在工程项目上的应用情况及效益分析
人工智能·深度学习·机器学习·语言模型·制造
夏河始溢1 小时前
一八零、AG-UI:构建AI前端交互的统一协议
前端·人工智能·ui
deep_drink1 小时前
【经典论文精读(一)】Isomap:非线性降维的全局几何框架(Science 2000)
人工智能·算法·机器学习
羑悻的小杀马特1 小时前
零成本神器组合:用Docker+Uptime Kuma+cpolar打造永不掉线的远程监控系统!
运维·人工智能·docker·容器
龙山云仓1 小时前
No132:AI中国故事-对话老子——道法自然与AI设计:无为而治、柔弱胜刚强与复杂系统智慧
大数据·人工智能·机器学习
Data-Miner1 小时前
类似Pandas AI的几个数据分析处理智能体介绍
人工智能·数据分析·pandas