如何使用 AutoModel 保存与加载自定义模型

介绍

在原始BERT模型的基础上额外添加一些层,并把新架构的模型保存到本地。

然后使用 AutoModel 加载模型,这样更方便一点。我们不需要在本地一直保存这个模型的自定义的网络结构的 python文件。

custom.py

要保证 model 的python文件足够的干净,只有模型架构的代码。不然容易报错,导致模型权重保存到本地失败。

python 复制代码
from torch import nn
from transformers import BertModel, BertPreTrainedModel


class CustomBERTModel(BertPreTrainedModel):
    def __init__(self, config, *args, **kwargs):
        super().__init__(config, *args, **kwargs)
        self.bert = BertModel(config)
        self.linear = nn.Linear(config.hidden_size, config.hidden_size)
        self.post_init()

    def forward(self, input_ids, attention_mask=None, token_type_ids=None):
        outputs = self.bert(
            input_ids=input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
        )
        logits = outputs[0]
        new_output = self.linear(logits)
        return new_output

# # 注册自定义模型到 AutoModel
# MODEL_MAPPING.register(AutoConfig, CustomBERTModel)

save_model.py

修改 linear 的权重,再把模型参数保存到本地。

python 复制代码
import torch
from torch import nn
from transformers import AutoTokenizer

from custom_BERT_model import CustomBERTModel

CustomBERTModel.register_for_auto_class("AutoModel")
model_name = "google-bert/bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = CustomBERTModel.from_pretrained(model_name)
config = model.config
model.linear.weight = nn.Parameter(torch.zeros(config.hidden_size, config.hidden_size))
model.linear.bias = nn.Parameter(torch.ones(config.hidden_size))
model.save_pretrained("custom_bert_model")
tokenizer.save_pretrained("custom_bert_model")

保存的文件如下:

复制代码
.
├── config.json
├── custom_BERT_model.py
├── model.safetensors
├── special_tokens_map.json
├── tokenizer_config.json
├── tokenizer.json
└── vocab.txt

上述代码注意
CustomBERTModel.register_for_auto_class("AutoModel")。只有写了这行代码,保存的文件里面才会有custom_BERT_model.py

模型加载

【注意】:
AutoModel.from_pretrained(save_directory, trust_remote_code=True),trust_remote_code 设置为True才能加载自定义模型结构的模型,否则加载的就是原始的BERT的结构。

python 复制代码
from transformers import AutoModel, AutoTokenizer
save_directory = "custom_bert_model"
tokenizer = AutoTokenizer.from_pretrained(save_directory)
loaded_model = AutoModel.from_pretrained(save_directory, trust_remote_code=True)

text = "Hello World!"
tokenized_text = tokenizer(text, return_tensors="pt")
print(tokenized_text)
print(loaded_model(**tokenized_text))

输出:

复制代码
tensor([[[1., 1., 1.,  ..., 1., 1., 1.],
         [1., 1., 1.,  ..., 1., 1., 1.],
         [1., 1., 1.,  ..., 1., 1., 1.],
         [1., 1., 1.,  ..., 1., 1., 1.],
         [1., 1., 1.,  ..., 1., 1., 1.]]], grad_fn=<ViewBackward0>)

无论输入的文本是什么,输出都是全1的矩阵,这是因为在前面我们修改linear层的参数。

相关推荐
孟祥_成都6 小时前
【全网最通俗!新手到AI全栈开发必读】 AI 是如何进化到大模型的
前端·人工智能·全栈
牛奶7 小时前
AI辅助开发的基础概念
前端·人工智能·ai编程
东坡肘子7 小时前
OpenClaw 不错,但我好像没有那么需要 -- 肘子的 Swift 周报 #125
人工智能·swiftui·swift
风象南14 小时前
普通人用AI加持赚到的第一个100块
人工智能·后端
牛奶15 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶15 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
罗西的思考18 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
冬奇Lab18 小时前
OpenClaw 源码精读(2):Channel & Routing——一条消息如何找到它的 Agent?
人工智能·开源·源码阅读
冬奇Lab18 小时前
一天一个开源项目(第38篇):Claude Code Telegram - 用 Telegram 远程用 Claude Code,随时随地聊项目
人工智能·开源·资讯
格砸20 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端