[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()
相关推荐
青主创享阁18 分钟前
玄晶引擎XgenCore Works V2.8.1升级解析 技术迭代赋能场景 代理模式全新落地
大数据·人工智能·代理模式
大写-凌祁1 小时前
OpenClaw 腾讯云服务本地访问配置指南
人工智能·云计算·腾讯云·agi
计算机科研狗@OUC1 小时前
(cvpr25) MP-HSIR: 面向通用高光谱图像复原的多提示框架
人工智能·深度学习·图像修复·高光谱图像
桃花猿1 小时前
大模型Token入门详解:概念、原理、换算与核心作用【AI基础】
人工智能·chatgpt
uesowys1 小时前
腾讯云使用OpenClaw搭建企业微信AI助手
人工智能·企业微信·腾讯云·openclaw
irpywp1 小时前
OpenShell:安全沙箱隔离的沙箱隔离技术
人工智能·安全
勾股导航5 小时前
大模型Skill
人工智能·python·机器学习
卷福同学7 小时前
【养虾日记】Openclaw操作浏览器自动化发文
人工智能·后端·算法
春日见7 小时前
如何入门端到端自动驾驶?
linux·人工智能·算法·机器学习·自动驾驶
光锥智能7 小时前
从自动驾驶到 AI 能力体系,元戎启行 GTC 发布基座模型新进展
人工智能