Hub Python 库文档
混入与序列化方法
并获得增强的文档体验
开始使用
混入与序列化方法
混入
huggingface_hub
库提供了一系列混入,可用作您对象的父类,以提供简单的上传和下载功能。请查看我们的集成指南,了解如何将任何机器学习框架与 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 序列化的参数。例如数据类、argparse.Namespace、OmegaConf 等。
用于将任何机器学习框架与 Hub 集成的通用混入。
要集成您的框架,您的模型类必须继承自此混入。保存/加载模型的自定义逻辑必须在 _from_pretrained
和 _save_pretrained
中覆盖。PyTorchModelHubMixin 是与 Hub 集成混入的一个很好的例子。请查看我们的集成指南以获取更多说明。
继承自 ModelHubMixin 时,您可以定义类级属性。这些属性不传递给 __init__
,而是传递给类定义本身。这对于定义集成 ModelHubMixin 的库的元数据很有用。
有关如何将混入与您的库集成的更多详细信息,请查看集成指南。
示例
>>> 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"
在子类中覆盖此方法以定义如何保存模型。请查看我们的集成指南以获取说明。
_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
, 可选) — Hub 上模型的修订版本。可以是分支名称、git 标签或任何提交 ID。默认为main
分支上的最新提交。 - force_download (
bool
, 可选, 默认为False
) — 是否强制(重新)从 Hub 下载模型权重和配置文件,覆盖现有缓存。 - proxies (
Dict[str, str]
, 可选) — 要按协议或端点使用的代理服务器字典(例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
)。 - token (
str
或bool
, 可选) — 用于远程文件的 HTTP bearer 授权令牌。默认情况下,它将使用运行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: 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
。 - 或者包含使用
save_pretrained
保存的模型权重的directory
路径,例如../path/to/my_model_directory/
。
- Hub 上模型的
- revision (
str
, 可选) — Hub 上模型的修订版本。可以是分支名称、git 标签或任何提交 ID。默认为main
分支上的最新提交。 - force_download (
bool
, 可选, 默认为False
) — 是否强制(重新)下载模型权重和配置文件,覆盖现有缓存。 - proxies (
Dict[str, str]
, 可选) — 要按协议或端点使用的代理服务器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理用于每个请求。 - token (
str
或bool
, 可选) — 用于远程文件的 HTTP bearer 授权令牌。默认情况下,它将使用运行hf auth login
时缓存的令牌。 - cache_dir (
str
,Path
, 可选) — 缓存文件存储的文件夹路径。 - local_files_only (
bool
, 可选, 默认为False
) — 如果为True
,则避免下载文件并返回本地缓存文件的路径(如果存在)。 - model_kwargs (
Dict
, 可选) — 模型初始化时传递给模型的附加关键字参数。
从 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
或DataclassInstance
, 可选) — 指定为键/值字典或数据类实例的模型配置。 - commit_message (
str
, 可选) — 推送时的提交消息。 - private (
bool
, 可选) — 创建的仓库是否应为私有。如果为None
(默认),则仓库将为公开,除非组织的默认设置为私有。 - token (
str
, 可选) — 用于远程文件的 HTTP bearer 授权令牌。默认情况下,它将使用运行hf auth login
时缓存的令牌。 - branch (
str
, 可选) — 推送模型的 git 分支。默认为"main"
。 - create_pr (
boolean
, 可选) — 是否从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_patterns
和 ignore_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 ) → str
或 None
参数
- save_directory (
str
或Path
) — 保存模型权重和配置的目录路径。 - config (
dict
或DataclassInstance
, 可选) — 以键/值字典或数据类实例形式指定的模型配置。 - 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 上提交的 URL,否则为 None
。
将权重保存在本地目录中。
PyTorch
实现了 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
实现了 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 (
str
或os.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,因为我们在 huggingface.co 上使用基于 Git 的系统存储模型和其他工件,所以revision
可以是 Git 允许的任何标识符。 - 包含使用
save_pretrained
保存的模型权重的目录
路径,例如./my_model_directory/
。 - 如果您同时提供了配置和状态字典(分别使用关键字参数
config
和state_dict
),则为None
。
- 字符串,huggingface.co 上模型存储库中托管的预训练模型的
- force_download (
bool
, 可选, 默认为False
) — 是否强制(重新)下载模型权重和配置文件,如果存在缓存版本则覆盖。 - proxies (
Dict[str, str]
, 可选) — 要按协议或端点使用的代理服务器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理在每个请求上使用。 - token (
str
或bool
, 可选) — 用作远程文件 HTTP 持有者授权的令牌。如果为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 持有者授权的令牌。如果未设置,将使用通过hf auth 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_patterns
和 ignore_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 (
str
或Path
) — 指定要保存 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 revision: typing.Optional[str] = None )
参数
- repo_id (
str
) — 存储 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 文件和指示用于构建fastai.Learner
的 fastai 和 fastcore 版本的 pyproject.toml 的目录。例如:./my_model_directory/
。
- 托管在 Hugging Face Hub 上。例如:'espejelomar/fatai-pet-breeds-classification' 或 'distilgpt2'。您可以通过在
- 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 承载授权的 Hugging Face 帐户令牌。如果为
None
,将通过提示请求令牌。 - config (dict, 可选) — 要与模型权重一起保存的配置对象。
- branch (str, 可选) — 推送模型所用的 git 分支。默认为存储库中指定的默认分支,即 “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_patterns 和 ignore_patterns 精确过滤要推送到 hub 的文件。使用 delete_patterns 在同一提交中删除现有远程文件。有关更多详细信息,请参阅 [upload_folder] 参考。
引发以下错误
- ValueError 如果用户未登录 Hugging Face Hub。