[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()
相关推荐
硅谷秋水4 小时前
WLA³:面向语义、动力学与运动学的世界潜动作建模
人工智能·机器学习·计算机视觉·语言模型·机器人
@陈小鱼4 小时前
基于CNN-Transformer的无袖带血压估计
人工智能·深度学习·神经网络·算法·cnn·transformer·血压
cu1434 小时前
细谈GM7123C的具体功能与其应用
c语言·c++·人工智能·嵌入式硬件
W***25924 小时前
Work Agent长程任务深度解读:AI自主执行复杂工作的底层机制
大数据·人工智能
金科AI评测笔记4 小时前
App竞品数据平台信息整理
大数据·人工智能
Margrop4 小时前
Ubuntu 22.04 硬升 26.04 实录:6KB/s 的下载、缩水的镜像,和一块“暂停营业”的牌子
人工智能
pride.li4 小时前
ISP标定-BLC标定(Black Level Calibration,黑电平校准)
人工智能·计算机视觉·接口隔离原则
中伟视界4 小时前
绿色矿山国标明日施行:边缘AI与AI布控球技术落地
大数据·人工智能·#深度学习·#机器视觉·#工业ai·#边缘计算·#矿山智能化
王中阳Go4 小时前
读者问"你用的什么 Agent":3 个 AI 员工的分工表和工具链
人工智能·后端·ai编程
atsec5 小时前
从论坛走向未来:atsec赞助第30届通用评估准则用户论坛(CCUF)罗马研讨会
大数据·人工智能