Hub Python 库文档

Mixins & 序列化方法

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

Mixins & 序列化方法

Mixins

huggingface_hub 库提供了一系列 mixins,可以作为您对象的父类使用,以便提供简单的上传和下载功能。查看我们的 集成指南,了解如何将任何 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 (strList[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 设置为 otherlicense_name 已设置时使用。例如:”https://coqui.ai/cpml”
  • pipeline_tag (str, 可选) — pipeline 的标签。用于生成模型卡片。例如:“text-classification”。
  • tags (List[str], 可选) — 要添加到模型卡片的标签。用于生成模型卡片。例如:[“computer-vision”]
  • coders (Dict[Type, Tuple[Callable, Callable]], 可选) — 自定义类型及其编码器/解码器的字典。用于编码/解码默认情况下不可 JSON 序列化的参数。例如 dataclasses、argparse.Namespace、OmegaConf 等。

一个通用的 mixin,用于将任何机器学习框架与 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,
...         resume_download: Optional[bool] = None,
...         proxies: Optional[Dict] = None,
...         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 (strPath) — 将在其中保存模型权重和配置的目录的路径。

在子类中覆盖此方法以定义如何保存您的模型。查看我们的 集成指南 以获取说明。

_from_pretrained

< >

( model_id: str revision: typing.Optional[str] cache_dir: typing.Union[str, pathlib.Path, NoneType] force_download: bool proxies: typing.Optional[typing.Dict] resume_download: typing.Optional[bool] local_files_only: bool token: typing.Union[bool, str, NoneType] **model_kwargs )

参数

  • model_id (str) — 从 Huggingface Hub 加载的模型的 ID (例如 bigscience/bloom)。
  • revision (str, optional) — Hub 上模型的修订版本。可以是分支名称、git 标签或任何提交 ID。默认为 main 分支上的最新提交。
  • force_download (bool, optional, defaults to False) — 是否强制(重新)从 Hub 下载模型权重和配置文件,覆盖现有缓存。
  • proxies (Dict[str, str], optional) — 按协议或端点使用的代理服务器字典 (例如,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'})。
  • token (str or bool, optional) — 用作远程文件的 HTTP Bearer 授权的令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • cache_dir (str, Path, optional) — 缓存文件存储在其中的文件夹的路径。
  • local_files_only (bool, optional, defaults to False) — 如果为 True,则避免下载文件,如果本地缓存文件存在,则返回本地缓存文件的路径。
  • model_kwargs — 传递给 _from_pretrained() 方法的其他关键字参数。

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

使用 hf_hub_download()snapshot_download() 从 Hub 下载文件,然后再加载它们。大多数作为输入的 args 可以直接传递给这 2 个方法。如果需要,您可以使用 “model_kwargs” 向此方法添加更多参数。例如,PyTorchModelHubMixin._from_pretrained() 接受一个 map_location 参数作为输入,以设置模型应加载到的设备。

查看我们的 集成指南 以获取更多说明。

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, pathlib.Path] force_download: bool = False resume_download: typing.Optional[bool] = None proxies: typing.Optional[typing.Dict] = None token: typing.Union[bool, str, NoneType] = None cache_dir: typing.Union[str, pathlib.Path, NoneType] = None local_files_only: bool = False revision: typing.Optional[str] = None **model_kwargs )

参数

  • pretrained_model_name_or_path (str, Path) —
    • Hub 上托管的模型的 model_id (字符串),例如 bigscience/bloom
    • 或者一个 directory 的路径,其中包含使用 save_pretrained 保存的模型权重,例如,../path/to/my_model_directory/
  • revision (str, optional) — Hub 上模型的修订版本。可以是分支名称、git 标签或任何提交 ID。默认为 main 分支上的最新提交。
  • force_download (bool, optional, defaults to False) — 是否强制(重新)从 Hub 下载模型权重和配置文件,覆盖现有缓存。
  • proxies (Dict[str, str], optional) — 按协议或端点使用的代理服务器字典,例如,{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。代理用于每个请求。
  • token (str or bool, optional) — 用作远程文件的 HTTP Bearer 授权的令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • cache_dir (str, Path, optional) — 缓存文件存储在其中的文件夹的路径。
  • local_files_only (bool, optional, defaults to False) — 如果为 True,则避免下载文件,如果本地缓存文件存在,则返回本地缓存文件的路径。
  • model_kwargs (Dict, optional) — 初始化期间传递给模型的其他 kwargs。

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

push_to_hub

< >

( repo_id: str config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None commit_message: str = 'Push model using huggingface_hub.' private: typing.Optional[bool] = None token: typing.Optional[str] = None branch: typing.Optional[str] = None create_pr: typing.Optional[bool] = None allow_patterns: typing.Union[typing.List[str], str, NoneType] = None ignore_patterns: typing.Union[typing.List[str], str, NoneType] = None delete_patterns: typing.Union[typing.List[str], str, NoneType] = None model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None )

参数

  • repo_id (str) — 要推送到的仓库的 ID (示例:"username/my-model")。
  • config (dict or DataclassInstance, optional) — 模型配置,指定为键/值字典或数据类实例。
  • commit_message (str, optional) — 推送时提交的消息。
  • private (bool, optional) — 创建的仓库是否应为私有。如果为 None(默认值),则仓库将是公开的,除非组织的默认设置为私有。
  • token (str, optional) — 用作远程文件的 HTTP Bearer 授权的令牌。默认情况下,它将使用运行 huggingface-cli login 时缓存的令牌。
  • branch (str, optional) — 在其上推送模型的分支 git 分支。这默认为 "main"
  • create_pr (boolean, optional) — 是否从带有该提交的 branch 创建拉取请求。默认为 False
  • allow_patterns (List[str]str, 可选) — 如果提供,则仅推送与至少一个模式匹配的文件。
  • ignore_patterns (List[str]str, 可选) — 如果提供,则不推送与任何模式匹配的文件。
  • delete_patterns (List[str]str, 可选) — 如果提供,则与任何模式匹配的远程文件将从仓库中删除。
  • model_card_kwargs (Dict[str, Any], 可选) — 传递给模型卡片模板以自定义模型卡片的其他参数。

将模型检查点上传到 Hub。

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

save_pretrained

< >

( save_directory: typing.Union[str, pathlib.Path] config: typing.Union[dict, huggingface_hub.hub_mixin.DataclassInstance, NoneType] = None repo_id: typing.Optional[str] = None push_to_hub: bool = False model_card_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None **push_to_hub_kwargs ) strNone

参数

  • save_directory (strPath) — 模型权重和配置将保存在其中的目录的路径。
  • config (dictDataclassInstance, 可选) — 模型配置,指定为键/值字典或数据类实例。
  • 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() 方法的其他关键字参数。

返回值

strNone

如果 push_to_hub=True,则为 Hub 上提交的 url,否则为 None

在本地目录中保存权重。

PyTorch

class 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.org.cn/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

Keras

class huggingface_hub.KerasModelHubMixin

< >

( *args **kwargs )

ModelHubMixin 的实现,为 Keras 模型提供模型 Hub 上传/下载功能。

>>> import tensorflow as tf
>>> from huggingface_hub import KerasModelHubMixin


>>> class MyModel(tf.keras.Model, KerasModelHubMixin):
...     def __init__(self, **kwargs):
...         super().__init__()
...         self.config = kwargs.pop("config", None)
...         self.dummy_inputs = ...
...         self.layer = ...

...     def call(self, *args):
...         return ...


>>> # Initialize and compile the model as you normally would
>>> model = MyModel()
>>> model.compile(...)
>>> # Build the graph by training it or passing dummy inputs
>>> _ = model(model.dummy_inputs)
>>> # 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/super-cool-model")

huggingface_hub.from_pretrained_keras

< >

( *args **kwargs )

参数

  • pretrained_model_name_or_path (stros.PathLike) — 可以是以下之一:
    • 一个字符串,即托管在 huggingface.co 的模型仓库内的预训练模型的 model id。 有效的模型 ID 可以位于根级别,例如 bert-base-uncased,或命名空间在用户或组织名称下,例如 dbmdz/bert-base-german-cased
    • 您可以通过在 model_id 的末尾添加 @ 来添加 revision,就像这样: dbmdz/bert-base-german-cased@main。 Revision 是要使用的特定模型版本。 它可以是分支名称、标签名称或提交 ID,因为我们使用基于 git 的系统来存储 huggingface.co 上的模型和其他工件,因此 revision 可以是 git 允许的任何标识符。
    • 使用 save_pretrained 保存的模型权重的 directory 的路径,例如 ./my_model_directory/
    • None,如果您同时提供配置和状态字典(分别使用关键字参数 configstate_dict)。
  • force_download (bool, 可选, 默认为 False) — 是否强制(重新)下载模型权重和配置文件,覆盖缓存的版本(如果存在)。
  • proxies (Dict[str, str], 可选) — 要按协议或端点使用的代理服务器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。 代理用于每个请求。
  • token (strbool, 可选) — 用作远程文件的 HTTP bearer 授权的令牌。 如果为 True,将使用运行 transformers-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • cache_dir (Union[str, os.PathLike], 可选) — 如果不应使用标准缓存,则下载的预训练模型配置应缓存到的目录的路径。
  • local_files_only(bool, 可选, 默认为 False) — 是否仅查看本地文件(即,不尝试下载模型)。
  • model_kwargs (Dict, 可选) — model_kwargs 将在初始化期间传递给模型

从 Hub 上的预训练模型实例化预训练的 Keras 模型。 该模型应为 SavedModel 格式。

当您要使用私有模型时,需要传递 token=True

huggingface_hub.push_to_hub_keras

< >

( model repo_id: str config: typing.Optional[dict] = None commit_message: str = 'Push Keras model using huggingface_hub.' private: typing.Optional[bool] = None api_endpoint: typing.Optional[str] = None token: typing.Optional[str] = None branch: typing.Optional[str] = None create_pr: typing.Optional[bool] = None allow_patterns: typing.Union[typing.List[str], str, NoneType] = None ignore_patterns: typing.Union[typing.List[str], str, NoneType] = None delete_patterns: typing.Union[typing.List[str], str, NoneType] = None log_dir: typing.Optional[str] = None include_optimizer: bool = False tags: typing.Union[list, str, NoneType] = None plot_model: bool = True **model_save_kwargs )

参数

  • model (Keras.Model) — 您想要推送到 Hub 的 Keras 模型。该模型必须已编译和构建。
  • repo_id (str) — 要推送到的仓库 ID (示例: "username/my-model")。
  • commit_message (str, 可选, 默认为 “Add Keras model”) — 推送时提交的消息。
  • private (bool, 可选) — 创建的仓库是否应为私有。 如果为 None (默认值),则仓库将是公开的,除非组织的默认设置为私有。
  • api_endpoint (str, 可选) — 将模型推送到 Hub 时使用的 API 终端节点。
  • token (str, 可选) — 用作远程文件 HTTP Bearer 授权的令牌。如果未设置,将使用使用 huggingface-cli login 登录时设置的令牌 (存储在 ~/.huggingface 中)。
  • branch (str, 可选) — 将模型推送到的 git 分支。 默认为仓库中指定的默认分支,默认为 "main"
  • create_pr (boolean, 可选) — 是否从带有该提交的 branch 创建拉取请求。 默认为 False
  • config (dict, 可选) — 要与模型权重一起保存的配置对象。
  • allow_patterns (List[str]str, 可选) — 如果提供,则仅推送与至少一个模式匹配的文件。
  • ignore_patterns (List[str]str, 可选) — 如果提供,则不推送与任何模式匹配的文件。
  • delete_patterns (List[str]str, 可选) — 如果提供,则与任何模式匹配的远程文件将从仓库中删除。
  • log_dir (str, 可选) — 要推送的 TensorBoard 日志目录。 如果仓库中包含日志文件,则 Hub 会自动托管和显示 TensorBoard 实例。
  • include_optimizer (bool, 可选, 默认为 False) — 是否在序列化期间包含优化器。
  • tags (Union[list, str], 可选) — 与模型相关的标签列表或单个标签的字符串。 请参阅此处的示例标签。
  • plot_model (bool, 可选, 默认为 True) — 设置为 True 将绘制模型并将其放入模型卡片中。 需要安装 graphviz 和 pydot。
  • model_save_kwargs(dict, 可选) — model_save_kwargs 将传递给 tf.keras.models.save_model()

将模型检查点上传到 Hub。

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

huggingface_hub.save_pretrained_keras

< >

( model save_directory: typing.Union[str, pathlib.Path] config: typing.Optional[typing.Dict[str, typing.Any]] = None include_optimizer: bool = False plot_model: bool = True tags: typing.Union[list, str, NoneType] = None **model_save_kwargs )

参数

  • model (Keras.Model) — 您想要保存的 Keras 模型。该模型必须已编译和构建。
  • save_directory (strPath) — 指定您想要在其中保存 Keras 模型的目录。
  • config (dict, 可选) — 要与模型权重一起保存的配置对象。
  • include_optimizer(bool, 可选, 默认为 False) — 是否在序列化中包含优化器。
  • plot_model (bool, 可选, 默认为 True) — 设置为 True 将绘制模型并将其放入模型卡片中。 需要安装 graphviz 和 pydot。
  • tags (Union[str,list], 可选) — 与模型相关的标签列表或单个标签的字符串。 请参阅此处的示例标签。
  • model_save_kwargs(dict, 可选) — model_save_kwargs 将传递给 tf.keras.models.save_model()

以 SavedModel 格式将 Keras 模型保存到 save_directory。 如果您使用的是 Functional 或 Sequential API,请使用此方法。

Fastai

huggingface_hub.from_pretrained_fastai

  • repo_id (str) — fastai.Learner 的 pickle 文件所在的位置。它可以是以下两者之一:
    • 托管在 Hugging Face Hub 上。例如:‘espejelomar/fatai-pet-breeds-classification’ 或 ‘distilgpt2’。您可以通过在 repo_id 末尾添加 @ 来添加 revision。例如:dbmdz/bert-base-german-cased@main。Revision 是要使用的特定模型版本。由于我们使用基于 git 的系统来存储 Hugging Face Hub 上的模型和其他工件,因此它可以是分支名称、标签名称或提交 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

< >

( learner repo_id: str commit_message: str = 'Push FastAI model using huggingface_hub.' private: typing.Optional[bool] = None token: typing.Optional[str] = None config: typing.Optional[dict] = None branch: typing.Optional[str] = None create_pr: typing.Optional[bool] = None allow_patterns: typing.Union[typing.List[str], str, NoneType] = None ignore_patterns: typing.Union[typing.List[str], str, NoneType] = None delete_patterns: typing.Union[typing.List[str], str, NoneType] = None api_endpoint: typing.Optional[str] = None )

参数

  • learner (Learner) — 您想要推送到 Hub 的 *fastai.Learner’。
  • repo_id (str) — Hub 中模型的仓库 ID,格式为 “namespace/repo_name”。命名空间可以是您的个人帐户或您拥有写入权限的组织(例如,‘stanfordnlp/stanza-de’)。
  • commit_message (str`,可选*) — 推送时提交的消息。默认为 "add model"
  • private (bool, 可选) — 创建的仓库是否应为私有。如果为 None(默认值),则默认为公开,除非组织的默认设置为私有。
  • token (str, 可选) — 用作远程文件的 HTTP Bearer 授权的 Hugging Face 帐户令牌。如果为 None,将通过提示询问令牌。
  • config (dict, 可选) — 要与模型权重一起保存的配置对象。
  • branch (str, 可选) — 在其上推送模型的分支。 这默认为存储库中指定的默认分支,默认情况下为“main”
  • create_pr (boolean, 可选) — 是否从带有该提交的 branch 创建拉取请求。 默认为 False
  • api_endpoint (str, 可选) — 将模型推送到 hub 时要使用的 API 端点。
  • allow_patterns (List[str]str, 可选) — 如果提供,则仅推送与至少一个模式匹配的文件。
  • ignore_patterns (List[str]str, 可选) — 如果提供,则不推送与任何模式匹配的文件。
  • delete_patterns (List[str]str, 可选) — 如果提供,则将从仓库中删除与任何模式匹配的远程文件。

将 learner 检查点文件上传到 Hub。

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

引发以下错误

  • ValueError 如果用户未登录到 Hugging Face Hub。
< > Update 在 GitHub 上更新