[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()
相关推荐
weixin_397574094 分钟前
企业智能体平台部署上线全流程:从环境搭建到智能体配置实操
人工智能
QZ166560951598 分钟前
动态感知·全覆盖管控·符合司法要求:通用行业知形数据库风险监测合规落地方案
大数据·人工智能
Kobebryant-Manba16 分钟前
深度学习时候d2l报错和使用问题
人工智能·深度学习
HackTwoHub19 分钟前
Sqli-Scanner SQL注入SKILL自动化挖掘SQL注入,零依赖自动化SQL注入挖掘,赏金猎人
数据库·人工智能·sql·web安全·网络安全·自动化·系统安全
GEO优化小助手24 分钟前
2026临沂GEO优化公司实测解析:3家本土机构适配性参考
大数据·人工智能·python
NeilYuen25 分钟前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss
unique28 分钟前
AI Coding 工具使用监控 — 市场竞品调研报告
人工智能·ai编程
环球科讯30 分钟前
爱征信 惠民生 促发展——建行江西省新余市分行开展征信知识进商户宣讲活动
人工智能
Dick50731 分钟前
ROS2 常用命令表
人工智能·学习·算法·机器人
云烟成雨TD31 分钟前
Agent Scope Java 2.x 系列【19】Harness:从零搭建 MySQL 文件系统
java·人工智能·agent