Transformers documentation

自定义模型

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

自定义模型

Transformers 模型旨在支持自定义。模型的代码完全包含在 Transformers 仓库的 model 子文件夹中。每个文件夹都包含一个 modeling.py 和一个 configuration.py 文件。复制这些文件即可开始自定义模型。

如果您要创建一个全新的模型,从零开始可能更简单。但对于与 Transformers 中现有模型非常相似的模型,复用或子类化相同的配置和模型类会更快。

本指南将向您展示如何自定义 ResNet 模型、启用 AutoClass 支持,并将其共享到 Hub。

配置

由基类 PreTrainedConfig 给出的配置包含了构建模型所需的所有信息。在这里,您将配置自定义 ResNet 模型的属性。不同的属性对应不同的 ResNet 模型类型。

自定义配置的主要规则如下:

  1. A custom configuration must subclass PreTrainedConfig. This ensures a custom model has all the functionality of a Transformers’ model such as from_pretrained(), save_pretrained(), and push_to_hub().
  2. PreTrainedConfig 的 __init__ 必须接受任意 kwargs,并且必须将它们传递给父类的 __init__。PreTrainedConfig 包含的字段比自定义配置中设置的字段更多,因此在使用 from_pretrained() 加载配置时,这些字段需要被你的配置接受并传递给父类。

检查某些参数的有效性是很有用的。在下面的示例中,实现了一个检查,以确保 block_type 和 stem_type 属于预定义值之一。

在配置类中添加 model_type,以启用 AutoClass 支持。

from transformers import PreTrainedConfig
from typing import List

class ResnetConfig(PreTrainedConfig):
    model_type = "resnet"

    def __init__(
        self,
        block_type="bottleneck",
        layers: list[int] = [3, 4, 6, 3],
        num_classes: int = 1000,
        input_channels: int = 3,
        cardinality: int = 1,
        base_width: int = 64,
        stem_width: int = 64,
        stem_type: str = "",
        avg_down: bool = False,
        **kwargs,
    ):
        if block_type not in ["basic", "bottleneck"]:
            raise ValueError(f"`block_type` must be 'basic' or bottleneck', got {block_type}.")
        if stem_type not in ["", "deep", "deep-tiered"]:
            raise ValueError(f"`stem_type` must be '', 'deep' or 'deep-tiered', got {stem_type}.")

        self.block_type = block_type
        self.layers = layers
        self.num_classes = num_classes
        self.input_channels = input_channels
        self.cardinality = cardinality
        self.base_width = base_width
        self.stem_width = stem_width
        self.stem_type = stem_type
        self.avg_down = avg_down
        super().__init__(**kwargs)

使用 save_pretrained() 将配置保存为自定义模型文件夹 custom-resnet 中的 JSON 文件。

resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
resnet50d_config.save_pretrained("custom-resnet")

模型

使用自定义的 ResNet 配置,你现在可以创建并自定义模型。该模型继承自基类 PreTrainedModel。与 PreTrainedConfig 类似,继承 PreTrainedModel 并使用配置初始化父类,可以将 Transformers 的功能(例如保存和加载)扩展到自定义模型中。

Transformers 的模型遵循在 __init__ 方法中接受 config 对象的约定。这样会将完整的 config 传递给模型的子层,而不是将 config 对象拆分为多个参数并分别传递给子层。

以这种方式编写模型可以生成更简洁的代码,并为任何超参数提供明确的唯一事实来源。此外,这也使得复用来自其他 Transformers 模型的代码变得更加容易。

你将创建两个 ResNet 模型:一个仅输出隐藏状态的极简 ResNet 模型,以及一个带有图像分类头的 ResNet 模型。

ResnetModel
ResnetModelForImageClassification

定义块类型与类之间的映射关系。其余部分通过将配置类传递给 ResNet 模型类来创建。

在模型类中添加 config_class 以启用 AutoClass 支持。

from transformers import PreTrainedModel
from timm.models.resnet import BasicBlock, Bottleneck, ResNet
from .configuration_resnet import ResnetConfig

BLOCK_MAPPING = {"basic": BasicBlock, "bottleneck": Bottleneck}

class ResnetModel(PreTrainedModel):
    config_class = ResnetConfig

    def __init__(self, config):
        super().__init__(config)
        block_layer = BLOCK_MAPPING[config.block_type]
        self.model = ResNet(
            block_layer,
            config.layers,
            num_classes=config.num_classes,
            in_chans=config.input_channels,
            cardinality=config.cardinality,
            base_width=config.base_width,
            stem_width=config.stem_width,
            stem_type=config.stem_type,
            avg_down=config.avg_down,
        )

    def forward(self, tensor):
        return self.model.forward_features(tensor)

模型可以返回任意输出格式。当标签可用时,返回包含损失的字典(例如 ResnetModelForImageClassification)可使自定义模型与 Trainer 兼容。对于其他输出格式,您需要使用自己的训练循环或采用其他训练库。

使用配置实例化自定义模型类。

resnet50d = ResnetModelForImageClassification(resnet50d_config)

此时,您可以将预训练权重加载到模型中,也可以从头开始训练。在本指南中,您将加载预训练权重。

从 timm 库加载预训练权重,然后使用 load_state_dict 将这些权重转移到自定义模型中。

import timm

pretrained_model = timm.create_model("resnet50d", pretrained=True)
resnet50d.model.load_state_dict(pretrained_model.state_dict())

AutoClass

AutoClass API 是一种快捷方式,用于为指定模型自动加载正确的架构。对于加载您自定义模型的用户来说,启用此功能会非常方便。

请确保配置类中包含 model_type 属性(必须与现有的模型类型不同),并且模型类中包含 config_class 属性。使用 register() 方法将自定义配置和模型添加到 AutoClass API 中。

AutoConfig.register() 的第一个参数必须与自定义配置类中的 model_type 属性相匹配,而 AutoModel.register() 的第一个参数必须与自定义模型类的 config_class 相匹配。

from transformers import AutoConfig, AutoModel, AutoModelForImageClassification

AutoConfig.register("resnet", ResnetConfig)
AutoModel.register(ResnetConfig, ResnetModel)
AutoModelForImageClassification.register(ResnetConfig, ResnetModelForImageClassification)

您的自定义模型代码现在已与 AutoClass API 兼容。用户可以使用 AutoModel 或 AutoModelForImageClassification 类来加载该模型。

上传

将自定义模型上传到 Hub,以便其他用户轻松加载和使用。

请确保模型目录的结构正确,如下所示。该目录应包含:

  • modeling.py:包含 ResnetModel 和 ResnetModelForImageClassification 的代码。只要其他文件位于同一目录中,此文件就可以使用相对导入。

在复制 Transformers 的模型文件时,请将 modeling.py 文件顶部的所有相对导入替换为从 Transformers 导入。

  • configuration.py:包含 ResnetConfig 的代码。
  • __init__.py:可以为空,该文件允许将 Python resnet_model 作为模块使用。
.
└── resnet_model
    ├── __init__.py
    ├── configuration_resnet.py
    └── modeling_resnet.py

要共享模型,请导入 ResNet 模型和配置。

from resnet_model.configuration_resnet import ResnetConfig
from resnet_model.modeling_resnet import ResnetModel, ResnetModelForImageClassification

复制模型文件和配置文件中的代码。为确保 save_pretrained() 保存 AutoClass 对象,请调用 register_for_auto_class() 方法。此方法会修改配置 JSON 文件,以包含 AutoClass 对象及其映射。

对于模型,请根据任务选择合适的 AutoModelFor 类。

ResnetConfig.register_for_auto_class()
ResnetModel.register_for_auto_class("AutoModel")
ResnetModelForImageClassification.register_for_auto_class("AutoModelForImageClassification")

要将多个任务映射到模型,请直接编辑配置 JSON 文件中的 auto_map。

"auto_map": {
    "AutoConfig": "<your-repo-name>--<config-name>",
    "AutoModel": "<your-repo-name>--<config-name>",
    "AutoModelFor<Task>": "<your-repo-name>--<config-name>",    
},

创建配置和模型,并将预训练权重加载到其中。

resnet50d_config = ResnetConfig(block_type="bottleneck", stem_width=32, stem_type="deep", avg_down=True)
resnet50d = ResnetModelForImageClassification(resnet50d_config)

pretrained_model = timm.create_model("resnet50d", pretrained=True)
resnet50d.model.load_state_dict(pretrained_model.state_dict())

模型现已准备就绪,可以推送到 Hub。请从命令行或 notebook 中登录您的 Hugging Face 账户。

huggingface-CLI
notebook
hf auth login

在模型上调用 push_to_hub() 以将模型上传到 Hub。

resnet50d.push_to_hub("custom-resnet50d")

预训练权重、配置文件、modeling.py 和 configuration.py 文件现在都应上传到您命名空间下的 Hub 仓库 中。

由于自定义模型不使用与 Transformers 模型相同的建模代码,因此需要在 from_pretrained() 中添加 trust_remote_code=True 才能加载该模型。有关更多信息,请参阅加载 自定义模型 部分。

Update on GitHub