Hub Python 庫文件

Mixin 和序列化方法

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Mixin 和序列化方法

Mixin

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 (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 化的引數。例如:資料類、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,
...         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 local_files_only: bool token: typing.Union[str, bool, NoneType] **model_kwargs )

引數

  • model_id (str) — 要從 Huggingface Hub 載入的模型 ID(例如 bigscience/bloom)。
  • revision (str, 可選) — Hub 上模型的 revision。可以是分支名稱、git 標籤或任何 commit id。預設為 main 分支上的最新 commit。
  • force_download (bool, optional, 預設為 False) — 是否強制(重新)從 Hub 下載模型權重和配置檔案,覆蓋現有快取。
  • token (strbool, optional) — 用於遠端檔案進行 HTTP bearer 身份驗證的 token。預設情況下,它將使用執行 hf auth login 時快取的 token。
  • cache_dir (str, Path, optional) — 快取檔案的儲存目錄路徑。
  • local_files_only (bool, optional, 預設為 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 token: typing.Union[str, bool, 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) —
    • 模型的 model_id(字串),例如 bigscience/bloom
    • 或模型權重儲存目錄的路徑,使用 save_pretrained 儲存,例如 ../path/to/my_model_directory/
  • revision (str, optional) — Hub 上的模型版本。可以是分支名稱、git 標籤或任何 commit id。預設為 main 分支上的最新 commit。
  • force_download (bool, optional, 預設為 False) — 是否強制(重新)從 Hub 下載模型權重和配置檔案,覆蓋現有快取。
  • token (strbool, optional) — 用於遠端檔案進行 HTTP bearer 身份驗證的 token。預設情況下,它將使用執行 hf auth login 時快取的 token。
  • cache_dir (str, Path, optional) — 快取檔案的儲存目錄路徑。
  • local_files_only (bool, optional, 預設為 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[list[str], str, NoneType] = None ignore_patterns: typing.Union[list[str], str, NoneType] = None delete_patterns: typing.Union[list[str], str, NoneType] = None model_card_kwargs: typing.Optional[dict[str, typing.Any]] = None )

引數

  • repo_id (str) — 要推送到的倉庫 ID(例如:"username/my-model")。
  • config (dictDataclassInstance, optional) — 以鍵值字典或 dataclass 例項形式指定的模型配置。
  • commit_message (str, optional) — 推送時的提交訊息。
  • private (bool, optional) — 建立的倉庫是否應為私有。如果為 None(預設),則倉庫將為公共的,除非該組織的預設設定為私有。
  • token (str, optional) — 用於遠端檔案進行 HTTP bearer 身份驗證的 token。預設情況下,它將使用執行 hf auth login 時快取的 token。
  • branch (str, optional) — 要推送模型所在的 git 分支。預設為 "main"
  • create_pr (boolean, optional) — 是否在此提交中從 branch 建立一個 Pull Request。預設為 False
  • allow_patterns (list[str]str, optional) — 如果提供,則僅推送匹配至少一個模式的檔案。
  • ignore_patterns (list[str]str, optional) — 如果提供,則不推送匹配任何模式的檔案。
  • delete_patterns (list[str]str, optional) — 如果提供,則將從倉庫中刪除匹配任何模式的遠端檔案。
  • model_card_kwargs (dict[str, Any], optional) — 用於自定義模型卡的其他引數,將傳遞給模型卡模板。

將模型檢查點上傳到 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[dict[str, typing.Any]] = None **push_to_hub_kwargs ) strNone

引數

  • save_directory (str or Path) — 要儲存模型權重和配置的目錄路徑。
  • config (dict or DataclassInstance, optional) — 以鍵值對字典或資料類例項形式指定的模型配置。
  • push_to_hub (bool, optional, defaults to False) — 是否在儲存模型後將其推送到 Huggingface Hub。
  • repo_id (str, optional) — Hub 上您的儲存庫 ID。僅當 push_to_hub=True 時使用。如果未提供,則預設為資料夾名稱。
  • model_card_kwargs (dict[str, Any], optional) — 用於自定義模型卡的其他引數,將傳遞給模型卡模板。
  • 傳遞給 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.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: str revision: typing.Optional[str] = None )

引數

  • 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 是要使用的特定模型版本。由於我們使用基於 git 的系統來儲存 Hugging Face Hub 上的模型和其他工件,因此它可以是分支名稱、標籤名稱或提交 ID。
    • 本地託管。repo_id 將是一個包含 pickle 檔案和 pyproject.toml 的目錄,該檔案指示用於構建 fastai.Learner 的 fastai 和 fastcore 版本。例如:./my_model_directory/
  • revision (str, optional) — 下載儲存庫檔案時使用的修訂版本。請參閱 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[list[str], str, NoneType] = None ignore_patterns: typing.Union[list[str], str, NoneType] = None delete_patterns: typing.Union[list[str], str, NoneType] = None api_endpoint: typing.Optional[str] = None )

引數

  • learner (Learner) — 您要推送到 Hub 的 fastai.Learner。
  • repo_id (str) — Hub 上您模型的儲存庫 ID,格式為“namespace/repo_name”。namespace 可以是您的個人賬戶或您擁有寫入許可權的組織(例如,“stanfordnlp/stanza-de”)。
  • commit_message (str, optional) — 推送時要提交的訊息。預設為 "add model"
  • private (bool, optional) — 是否應將建立的儲存庫設為私有。如果為 None(預設),則預設為公開,除非該組織的預設設定是私有的。
  • token (str, optional) — 用於遠端檔案的 HTTP bearer 授權的 Hugging Face 賬戶 token。如果為 None,則將透過提示要求輸入 token。
  • 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, optional) — 如果提供,則僅推送匹配至少一個模式的檔案。
  • ignore_patterns (list[str]str, optional) — 如果提供,則不會推送匹配任何模式的檔案。
  • delete_patterns (list[str]str, optional) — 如果提供,將從倉庫中刪除與任何模式匹配的遠端檔案。

將 learner 的檢查點檔案上傳到 Hub。

使用 allow_patternsignore_patterns 精確過濾要推送到 Hub 的檔案。使用 delete_patterns 在同一個提交中刪除現有的遠端檔案。有關更多詳細資訊,請參閱 [upload_folder] 參考。

引發以下錯誤

  • ValueError 如果使用者未登入 Hugging Face Hub。
在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.