# Mixins 与序列化方法

## 混入

`huggingface_hub` 库提供了一系列混入类（mixins），可作为对象的父类，以提供简单的上传和下载功能。请参阅我们的 [集成指南](../guides/integrations)，了解如何将任意机器学习框架与 Hub 集成。

### 通用[[huggingface_hub.ModelHubMixin]]

#### huggingface_hub.ModelHubMixin[[huggingface_hub.ModelHubMixin]]

```python
huggingface_hub.ModelHubMixin(*args, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hub_mixin.py#L66)

**参数：**

repo_url (`str`, *可选*) : 库仓库的 URL。用于生成模型卡片。

paper_url (`str`, *可选*) : 库论文的 URL。用于生成模型卡片。

docs_url (`str`, *可选*) : 库文档的 URL。用于生成模型卡片。

model_card_template (`str`, *可选*) : 模型卡片的模板。用于生成模型卡片。默认为通用模板。

language (`str` 或 `list[str]`，*可选*)：该库支持的语言。用于生成模型卡片。

library_name (`str`, *可选*) : 集成 ModelHubMixin 的库的名称。用于生成模型卡片。

license (`str`, *可选*) : 集成 ModelHubMixin 的库的许可证。用于生成模型卡片。例如："apache-2.0"

license_name (`str`, *可选*) : 集成 ModelHubMixin 的库的名称。用于生成模型卡片。仅在 `license` 设置为 `other` 时使用。例如："coqui-public-model-license"。

license_link (`str`, *可选*) : 集成 ModelHubMixin 的库的许可证 URL。用于生成模型卡片。仅在 `license` 设置为 `other` 且 `license_name` 已设置时使用。例如："https://coqui.ai/cpml"。

pipeline_tag (`str`, *可选*) : 管道的标签。用于生成模型卡片。例如 "text-classification"。

tags (`list[str]`, *可选*) : 要添加到模型卡中的标签。用于生成模型卡。例如 ["computer-vision"]

coders (`dict[Type, tuple[Callable, Callable]]`，*可选*)：自定义类型及其编码器/解码器的字典。用于编码/解码默认情况下无法序列化为 JSON 的参数，例如 dataclasses、argparse.Namespace、OmegaConf 等。

一个通用混入类，用于将任意机器学习框架与 Hub 集成。

要将您的框架集成进来，您的模型类必须继承自此类。保存/加载模型的自定义逻辑必须在 `_from_pretrained` 和 `_save_pretrained` 中重写。[PyTorchModelHubMixin](/docs/huggingface_hub/v2.4.0/zh/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) 是与 Hub 进行 mixin 集成的良好示例。有关更多说明，请参阅我们的[集成指南](../guides/integrations)。

继承 [ModelHubMixin](/docs/huggingface_hub/v2.4.0/zh/package_reference/mixins#huggingface_hub.ModelHubMixin) 时，您可以定义类级别的属性。这些属性不会传递给 `__init__`，而是直接用于类定义本身。这对于定义集成 [ModelHubMixin](/docs/huggingface_hub/v2.4.0/zh/package_reference/mixins#huggingface_hub.ModelHubMixin) 的库的元数据非常有用。

有关如何将 mixin 集成到您的库中的更多详细信息，请参阅[集成指南](../guides/integrations)。

示例：

```python
>>> from huggingface_hub import ModelHubMixin

# Inherit from ModelHubMixin
>>> class MyCustomModel(
...         ModelHubMixin,
...         library_name="my-library",
...         tags=["computer-vision"],
...         repo_url="https://github.com/huggingface/my-cool-library",
...         paper_url="https://arxiv.org/abs/2304.12244",
...         docs_url="https://huggingface.co/docs/my-cool-library",
...         # ^ optional metadata to generate model card
...     ):
...     def __init__(self, size: int = 512, device: str = "cpu"):
...         # define how to initialize your model
...         super().__init__()
...         ...
...
...     def _save_pretrained(self, save_directory: Path) -> None:
...         # define how to serialize your model
...         ...
...
...     @classmethod
...     def from_pretrained(
...         cls: type[T],
...         pretrained_model_name_or_path: Union[str, Path],
...         *,
...         force_download: bool = False,
...         token: Optional[Union[str, bool]] = None,
...         cache_dir: Optional[Union[str, Path]] = None,
...         local_files_only: bool = False,
...         revision: Optional[str] = None,
...         **model_kwargs,
...     ) -> T:
...         # define how to deserialize your model
...         ...

>>> model = MyCustomModel(size=256, device="gpu")

# Save model weights to local directory
>>> model.save_pretrained("my-awesome-model")

# Push model weights to the Hub
>>> model.push_to_hub("my-awesome-model")

# Download and initialize weights from the Hub
>>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model")
>>> reloaded_model.size
256

# Model card has been correctly populated
>>> from huggingface_hub import ModelCard
>>> card = ModelCard.load("username/my-awesome-model")
>>> card.data.tags
["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"]
>>> card.data.library_name
"my-library"
```

#### _save_pretrained[[huggingface_hub.ModelHubMixin._save_pretrained]]

```python
_save_pretrained(save_directory: Path)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hub_mixin.py#L440)

**参数：**

save_directory (`str` 或 `Path`)：用于保存模型权重和配置的目录路径。

在子类中重写此方法以定义如何保存模型。有关说明，请参阅我们的[集成指南](../guides/integrations)。

#### _from_pretrained[[huggingface_hub.ModelHubMixin._from_pretrained]]

```python
_from_pretrained(model_id: str, revision: str | None, cache_dir: str | pathlib.Path | None, force_download: bool, local_files_only: bool, token: str | bool | None, **model_kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hub_mixin.py#L567)

**参数：**

model_id (`str`) : 要从 Huggingface Hub 加载的模型 ID（例如 `bigscience/bloom`）。

revision (`str`, *可选*) : Hub 上模型的版本。可以是分支名称、git 标签或任何提交 ID。默认值为 `main` 分支上的最新提交。

force_download (`bool`, *可选*，默认为 `False`)：是否强制从 Hub 重新下载模型权重和配置文件，覆盖现有缓存。

token (`str` 或 `bool`，*可选*) : 用于远程文件的 HTTP 承载者授权令牌。默认情况下，它将使用运行 `hf auth login` 时缓存的令牌。

cache_dir (`str`, `Path`, *可选*) : 缓存文件存储文件夹的路径。

local_files_only (`bool`，*可选*，默认为 `False`)：如果为 `True`，则避免下载文件，并在本地缓存文件存在时返回其路径。

model_kwargs : 传递给 [_from_pretrained()](/docs/huggingface_hub/v2.4.0/zh/package_reference/mixins#huggingface_hub.ModelHubMixin._from_pretrained) 方法的额外关键字参数。

在子类中重写此方法，以定义如何从预训练模型加载您的模型。

在加载文件之前，请使用 [hf_hub_download()](/docs/huggingface_hub/v2.4.0/zh/package_reference/file_download#huggingface_hub.hf_hub_download) 或 [snapshot_download()](/docs/huggingface_hub/v2.4.0/zh/package_reference/file_download#huggingface_hub.snapshot_download) 从 Hub 下载文件。作为输入的大多数参数都可以直接传递给这两个方法。如有需要，您可以通过 "model_kwargs" 向此方法添加更多参数。例如，`PyTorchModelHubMixin._from_pretrained()` 接受一个 `map_location` 参数，用于设置模型应加载到的设备。

请参阅我们的[集成指南](../guides/integrations)以获取更多说明。

#### from_pretrained[[huggingface_hub.ModelHubMixin.from_pretrained]]

```python
from_pretrained(pretrained_model_name_or_path: str | pathlib.Path, force_download: bool = False, token: str | bool | None = None, cache_dir: str | pathlib.Path | None = None, local_files_only: bool = False, revision: str | None = None, **model_kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hub_mixin.py#L451)

**参数：**

pretrained_model_name_or_path (`str`, `Path`) : - 托管在 Hub 上的模型的 `model_id`（字符串），例如 `bigscience/bloom`。 - 或者一个指向 `directory` 的路径，该目录包含使用 `save_pretrained` 保存的模型权重，例如 `../path/to/my_model_directory/`。

revision (`str`, *可选*) : Hub 上模型的版本。可以是分支名称、git 标签或任何提交 ID。默认值为 `main` 分支上的最新提交。

force_download (`bool`, *可选*，默认为 `False`)：是否强制从 Hub 重新下载模型权重和配置文件，覆盖现有缓存。

token (`str` 或 `bool`，*可选*) : 用于远程文件的 HTTP 承载者授权令牌。默认情况下，它将使用运行 `hf auth login` 时缓存的令牌。

cache_dir (`str`, `Path`, *可选*) : 缓存文件存储文件夹的路径。

local_files_only (`bool`，*可选*，默认为 `False`)：如果为 `True`，则避免下载文件，并在本地缓存文件存在时返回其路径。

model_kwargs (`dict`, *可选*) : 在初始化期间传递给模型的额外关键字参数。

从 Huggingface Hub 下载模型并实例化它。

#### push_to_hub[[huggingface_hub.ModelHubMixin.push_to_hub]]

```python
push_to_hub(repo_id: str, config: dict | huggingface_hub.hub_mixin.DataclassInstance | None = None, commit_message: str = 'Push model using huggingface_hub.', private: bool | None = None, token: str | None = None, branch: str | None = None, create_pr: bool | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, delete_patterns: list[str] | str | None = None, model_card_kwargs: dict[str, typing.Any] | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hub_mixin.py#L609)

**参数：**

repo_id (`str`) : 要推送到的仓库的 ID（示例：`"username/my-model"`）。

config (`dict` 或 `DataclassInstance`，*可选*)：以键值字典或 dataclass 实例形式指定的模型配置。

commit_message (`str`, *可选*) : 推送时提交的提交信息。

private (`bool`, *可选*) : 创建的仓库是否应为私有。如果为 `None`（默认值），除非组织的默认设置为私有，否则仓库将是公开的。

token (`str`, *可选*) : 用于远程文件的 HTTP 承载者授权令牌。默认情况下，它将使用运行 `hf auth login` 时缓存的令牌。

branch (`str`, *可选*) : 推送模型所在的 git 分支。默认值为 `"main"`。

create_pr (`boolean`, *可选*) : 是否从 `branch` 创建包含该提交的 Pull Request。默认为 `False`。

allow_patterns (`list[str]` 或 `str`，*可选*)：如果提供，则仅推送至少匹配其中一个模式的文件。

ignore_patterns (`list[str]` 或 `str`，*可选*) : 如果提供，则匹配任一模式的文件不会被推送。

delete_patterns (`list[str]` 或 `str`，*可选*) : 如果提供，与其中任一模式匹配的远程文件将从仓库中删除。

model_card_kwargs (`dict[str, Any]`, *可选*) : 传递给模型卡片模板以自定义模型卡片的额外参数。

**返回：**

在给定仓库中，您的模型提交（commit）的 URL。

将模型检查点上传到 Hub。

使用 `allow_patterns` 和 `ignore_patterns` 来精确筛选应推送到 hub 的文件。使用 `delete_patterns` 可在同一提交中删除现有的远程文件。有关更多详细信息，请参阅 [upload_folder()](/docs/huggingface_hub/v2.4.0/zh/package_reference/hf_api#huggingface_hub.HfApi.upload_folder) 参考文档。

#### save_pretrained[[huggingface_hub.ModelHubMixin.save_pretrained]]

```python
save_pretrained(save_directory: str | pathlib.Path, config: dict | huggingface_hub.hub_mixin.DataclassInstance | None = None, repo_id: str | None = None, push_to_hub: bool = False, model_card_kwargs: dict[str, typing.Any] | None = None, **push_to_hub_kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hub_mixin.py#L372)

**参数：**

save_directory (`str` 或 `Path`)：用于保存模型权重和配置的目录路径。

config (`dict` 或 `DataclassInstance`，*可选*)：以键值字典或 dataclass 实例形式指定的模型配置。

push_to_hub (`bool`, *可选*, 默认为 `False`) : 是否在保存模型后将其推送到 Huggingface Hub。

repo_id (`str`, *可选*) : 您在 Hub 上的仓库 ID。仅在 `push_to_hub=True` 时使用。如果未提供，则默认为文件夹名称。

model_card_kwargs (`dict[str, Any]`, *可选*) : 传递给模型卡片模板以自定义模型卡片的额外参数。

push_to_hub_kwargs : 传递给 [push_to_hub()](/docs/huggingface_hub/v2.4.0/zh/package_reference/mixins#huggingface_hub.ModelHubMixin.push_to_hub) 方法的额外关键字参数。

**返回：** `str` 或 `None`

如果 `push_to_hub=True`，则为 Hub 上该 commit 的 url，否则为 `None`。

在本地目录中保存权重。

### PyTorch[[huggingface_hub.PyTorchModelHubMixin]]

#### huggingface_hub.PyTorchModelHubMixin[[huggingface_hub.PyTorchModelHubMixin]]

```python
huggingface_hub.PyTorchModelHubMixin(*args, **kwargs)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/hub_mixin.py#L692)

[ModelHubMixin](/docs/huggingface_hub/v2.4.0/zh/package_reference/mixins#huggingface_hub.ModelHubMixin) 的实现，为 PyTorch 模型提供模型 Hub 上传/下载功能。模型默认使用 `model.eval()` 设置为评估模式（dropout 模块被禁用）。若要训练模型，应首先使用 `model.train()` 将其切换回训练模式。

有关如何使用该 mixin 的更多详细信息，请参阅 [ModelHubMixin](/docs/huggingface_hub/v2.4.0/zh/package_reference/mixins#huggingface_hub.ModelHubMixin)。

示例：

```python
>>> import torch
>>> import torch.nn as nn
>>> from huggingface_hub import PyTorchModelHubMixin

>>> class MyModel(
...         nn.Module,
...         PyTorchModelHubMixin,
...         library_name="keras-nlp",
...         repo_url="https://github.com/keras-team/keras-nlp",
...         paper_url="https://arxiv.org/abs/2304.12244",
...         docs_url="https://keras.io/keras_nlp/",
...         # ^ optional metadata to generate model card
...     ):
...     def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
...         super().__init__()
...         self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
...         self.linear = nn.Linear(output_size, vocab_size)

...     def forward(self, x):
...         return self.linear(x + self.param)
>>> model = MyModel(hidden_size=256)

# Save model weights to local directory
>>> model.save_pretrained("my-awesome-model")

# Push model weights to the Hub
>>> model.push_to_hub("my-awesome-model")

# Download and initialize weights from the Hub
>>> model = MyModel.from_pretrained("username/my-awesome-model")
>>> model.hidden_size
256
```

### Fastai[[huggingface_hub.from_pretrained_fastai]]

#### huggingface_hub.from_pretrained_fastai[[huggingface_hub.from_pretrained_fastai]]

```python
huggingface_hub.from_pretrained_fastai(repo_id: str, revision: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/fastai_utils.py#L289)

**参数：**

repo_id (`str`) : 存放已序列化（pickled）的 fastai.Learner 的位置。可以是以下两种情况之一： - 托管在 Hugging Face Hub 上。例如：'espejelomar/fatai-pet-breeds-classification' 或 'distilgpt2'。您可以在 `repo_id` 末尾添加 `@` 来指定 `revision`。例如：`dbmdz/bert-base-german-cased@main`。Revision 是要使用的特定模型版本。由于我们在 Hugging Face Hub 上使用基于 git 的系统来存储模型和其他工件，因此它可以是分支名称、标签名称或提交 ID。 - 托管在本地。`repo_id` 将是一个包含 pickle 文件以及 pyproject.toml 文件的目录，该文件指明了用于构建 `fastai.Learner` 的 fastai 和 fastcore 版本。例如：`./my_model_directory/`。

revision (`str`, *可选*) : 下载仓库文件时所使用的修订版本。请参阅 `snapshot_download` 的文档。

**返回：**

`repo_id` 仓库中的 `fastai.Learner` 模型。

从 Hub 或本地目录加载预训练的 fastai 模型。

#### huggingface_hub.push_to_hub_fastai[[huggingface_hub.push_to_hub_fastai]]

```python
huggingface_hub.push_to_hub_fastai(learner, repo_id: str, commit_message: str = 'Push FastAI model using huggingface_hub.', private: bool | None = None, token: str | None = None, config: dict | None = None, branch: str | None = None, create_pr: bool | None = None, allow_patterns: list[str] | str | None = None, ignore_patterns: list[str] | str | None = None, delete_patterns: list[str] | str | None = None, api_endpoint: str | None = None)
```

[源代码](https://github.com/huggingface/huggingface_hub/blob/v2.4.0/src/huggingface_hub/fastai_utils.py#L334)

**参数：**

learner (*Learner*)：您希望推送到 Hub 的 *fastai.Learner'。

repo_id (*str*) : 您在 Hub 中模型的仓库 ID，格式为 "namespace/repo_name"。namespace 可以是您的个人账户，也可以是您拥有写入权限的组织（例如，'stanfordnlp/stanza-de'）。

commit_message (*str`, *optional*) : Message to commit while pushing. Will default to `"add model"`.

private (*bool*, *optional*) : 是否将创建的仓库设为私有。如果为 *None*（默认值），则默认为公开，除非该组织的默认设置为私有。

token (*str*, *optional*) : 用于远程文件的 HTTP 承载者授权的 Hugging Face 账户令牌。如果为 `None`，将通过提示请求令牌。

config (*dict*, *optional*) : 与模型权重一起保存的配置对象。

branch (*str*, *optional*) : 用于推送模型的 git 分支。默认值为您仓库中指定的默认分支，其默认值为 *"main"*。

create_pr (*boolean*, *optional*) : 是否从包含该提交的 *branch* 创建 Pull Request。默认为 *False*。

api_endpoint (*str*, *optional*) : 将模型推送到 hub 时使用的 API 端点。

allow_patterns (*list[str]* 或 *str*，*可选*)：如果提供，则仅推送至少匹配其中一个模式的文件。

ignore_patterns (*list[str]* 或 *str*，*可选*) : 如果提供，则匹配任一模式的文件不会被推送。

delete_patterns (*list[str]* 或 *str*，*可选*)：如果提供，则匹配任一模式的远程文件将从仓库中删除。

**返回：**

在给定仓库中，您的模型提交（commit）的 URL。

将学习者检查点文件上传到 Hub。

使用 *allow_patterns* 和 *ignore_patterns* 来精确筛选应推送到 hub 的文件。使用 *delete_patterns* 在同一提交中删除现有的远程文件。有关更多详细信息，请参阅 [*upload_folder*] 参考文档。

> [!TIP]
> 引发以下错误：
>
> - 如果用户未登录 Hugging Face Hub，则抛出 [*ValueError*](https://docs.python.org/3/library/exceptions.html#ValueError)。

