Hub Python Library documentation

Mixins 与序列化方法

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v2.4.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Mixins 与序列化方法

混入

huggingface_hub 库提供了一系列混入(mixin),可作为对象的父类,以提供简单的上传和下载功能。请参阅我们的 集成指南,了解如何将任意 ML 框架与 Hub 集成。

通用

class huggingface_hub.ModelHubMixin

< >

( *args**kwargs )

参数

  • 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 是与 Hub 进行 mixin 集成的良好示例。有关更多说明,请参阅我们的集成指南。

继承 ModelHubMixin 时,您可以定义类级别的属性。这些属性不会传递给 __init__,而是直接用于类定义本身。这对于定义集成 ModelHubMixin 的库的元数据非常有用。

有关如何将 mixin 集成到您的库中的更多详细信息,请参阅集成指南。

示例:

>>> 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

< >

( save_directory: Path )

参数

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

在子类中重写此方法以定义如何保存模型。 有关说明,请参阅我们的集成指南。

_from_pretrained

< >

( model_id: strrevision: str | Nonecache_dir: str | pathlib.Path | Noneforce_download: boollocal_files_only: booltoken: str | bool | None**model_kwargs )

参数

  • 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() 方法的额外关键字参数。

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

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

请参阅我们的集成指南以获取更多说明。

from_pretrained

< >

( pretrained_model_name_or_path: str | pathlib.Pathforce_download: bool = Falsetoken: str | bool | None = Nonecache_dir: str | pathlib.Path | None = Nonelocal_files_only: bool = Falserevision: str | None = None**model_kwargs )

参数

  • pretrained_model_name_or_path (str, Path) —
    • model_id(字符串),即托管在 Hub 上的模型的 ID,例如 bigscience/bloom。
    • Or a path to a directory containing model weights saved using save_pretrained, e.g., ../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, 可选) — 在初始化期间传递给模型的额外 kwargs。

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

push_to_hub

< >

( repo_id: strconfig: dict | huggingface_hub.hub_mixin.DataclassInstance | None = Nonecommit_message: str = 'Push model using huggingface_hub.'private: bool | None = Nonetoken: str | None = Nonebranch: str | None = Nonecreate_pr: bool | None = Noneallow_patterns: list[str] | str | None = Noneignore_patterns: list[str] | str | None = Nonedelete_patterns: list[str] | str | None = Nonemodel_card_kwargs: dict[str, typing.Any] | None = None )

参数

  • 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], 可选) — 传递给模型卡片模板以自定义模型卡片的额外参数。

将模型检查点上传到 Hub。

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

save_pretrained

< >

( save_directory: str | pathlib.Pathconfig: dict | huggingface_hub.hub_mixin.DataclassInstance | None = Nonerepo_id: str | None = Nonepush_to_hub: bool = Falsemodel_card_kwargs: dict[str, typing.Any] | None = None**push_to_hub_kwargs ) → str or None

参数

  • 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() 方法的额外关键字参数。

返回值

str 或 None

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

在本地目录中保存权重。

PyTorch

类 huggingface_hub.PyTorchModelHubMixin

< >

( *args**kwargs )

ModelHubMixin 的实现,为 PyTorch 模型提供模型 Hub 上传/下载功能。模型默认使用 model.eval() 设置为评估模式(dropout 模块被禁用)。若要训练模型,应首先使用 model.train() 将其切换回训练模式。

有关如何使用该 mixin 的更多详细信息,请参阅 ModelHubMixin。

示例:

>>> 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

< >

( repo_id: strrevision: str | None = None )

参数

  • repo_id (str) — 存放 pickle 格式 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 的文档。

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

huggingface_hub.push_to_hub_fastai

< >

( learnerrepo_id: strcommit_message: str = 'Push FastAI model using huggingface_hub.'private: bool | None = Nonetoken: str | None = Noneconfig: dict | None = Nonebranch: str | None = Nonecreate_pr: bool | None = Noneallow_patterns: list[str] | str | None = Noneignore_patterns: list[str] | str | None = Nonedelete_patterns: list[str] | str | None = Noneapi_endpoint: str | None = None )

参数

  • learner (Learner) — 您希望推送到 Hub 的 *fastai.Learner’。
  • repo_id (str) — 您在 Hub 中模型的仓库 ID,格式为“namespace/repo_name”。namespace 可以是您的个人账户,也可以是您拥有写入权限的组织(例如,‘stanfordnlp/stanza-de’)。
  • commit_message (str`, 可选*) — 推送时提交的提交信息。默认值为 "add model"。
  • private (bool, optional) — 是否应将创建的仓库设为私有。 如果为 None(默认值),则默认为公开,除非该组织的默认设置为私有。
  • token (str, 可选) — 用于远程文件的 HTTP 承载者授权的 Hugging Face 账户令牌。如果为 None,将通过提示请求输入令牌。
  • config (dict,可选) — 与模型权重一起保存的配置对象。
  • branch (str, optional) — 用于推送模型的 git 分支。默认值为您仓库中指定的默认分支,其默认值为 “main”。
  • create_pr (boolean, 可选) — 是否从 branch 创建包含该提交的 Pull Request。 默认为 False。
  • api_endpoint (str, 可选) — 将模型推送到 Hub 时使用的 API 端点。
  • allow_patterns (list[str] 或 str,可选) — 如果提供,则仅推送至少匹配其中一个模式的文件。
  • ignore_patterns (list[str] 或 str,可选) — 如果提供,则匹配任一模式的文件不会被推送。
  • delete_patterns (list[str] 或 str,可选) — 如果提供,则匹配其中任意模式的远程文件将从仓库中删除。

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

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

引发以下错误:

  • 如果用户未登录 Hugging Face Hub,则抛出 ValueError。
Update on GitHub