Hub Python 函式庫文件

Mixins 與序列化方法

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Mixin 與序列化方法

Mixin

huggingface_hub 函式庫提供了一系列 Mixin,可以用作您物件的父類別,以提供簡單的上傳和下載功能。請查看我們的整合指南,了解如何將任何機器學習框架與 Hub 進行整合。

通用 (Generic)

class huggingface_hub.ModelHubMixin

< >

( *args **kwargs )

參數

  • repo_url (str, 選填) — 函式庫儲存庫的 URL。用於產生模型卡 (model card)。
  • 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 的函式庫授權網址。用於產生模型卡。僅在 license 設定為 other 且已設定 license_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 等。

用於將「任何」機器學習框架與 Hub 整合的通用 Mixin。

若要整合您的框架,您的模型類別必須繼承自此類別。用於儲存/載入模型的自訂邏輯必須在 _from_pretrained_save_pretrained 中進行覆寫。PyTorchModelHubMixin 是將 Mixin 與 Hub 整合的良好範例。請查看我們的整合指南以獲取更多說明。

繼承 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: str | None cache_dir: str | pathlib.Path | None force_download: bool local_files_only: bool token: str | bool | None **model_kwargs )

參數

  • model_id (str) — 要從 Hugging Face Hub 載入的模型 ID (例如 bigscience/bloom)。
  • revision (str, 選填) — Hub 上的模型版本。可以是分支名稱、git 標籤或任何提交 ID。預設為 main 分支上的最新提交。
  • force_download (bool, 選填, 預設為 False) — 是否強制(重新)從 Hub 下載模型權重和設定檔,覆寫現有的快取。
  • token (strbool, 選填) — 用作遠端檔案 HTTP 持有者授權 (bearer authorization) 的權杖。預設會使用執行 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.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 )

參數

  • pretrained_model_name_or_path (str, Path) —
    • 託管於 Hub 上的模型 model_id (字串),例如 bigscience/bloom
    • 或是包含使用 save_pretrained 儲存之模型權重的目錄路徑,例如 ../path/to/my_model_directory/
  • revision (str, 選填) — Hub 上的模型版本。可以是分支名稱、git 標籤或任何提交 ID。預設為 main 分支上的最新提交。
  • force_download (bool, 選填, 預設為 False) — 是否強制(重新)從 Hub 下載模型權重和設定檔,覆寫現有的快取。
  • token (strbool, 選填) — 用作遠端檔案 HTTP 持有者授權的權杖。預設會使用執行 hf auth login 時快取的權杖。
  • cache_dir (str, Path, 選填) — 儲存快取檔案的資料夾路徑。
  • local_files_only (bool, 選填, 預設為 False) — 若設為 True,則避免下載檔案,若本地快取檔案存在,則直接回傳該檔案的路徑。
  • model_kwargs (dict, 選填) — 傳遞給模型初始化過程的額外 kwargs。

從 Hugging Face Hub 下載模型並實例化。

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 )

參數

  • repo_id (str) — 要推送到儲存庫的 ID (例如:"username/my-model")。
  • config (dictDataclassInstance, 選填) — 以鍵/值字典或 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_patternsignore_patterns 來精確篩選要推送到 Hub 的檔案。使用 delete_patterns 在同一次提交中刪除現有的遠端檔案。詳情請參閱 upload_folder() 參考文件。

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

參數

  • save_directory (strPath) — 用於儲存模型權重和設定檔的目錄路徑。
  • config (dictDataclassInstance, 選填) — 以鍵/值字典或 dataclass 實例指定的模型設定。
  • push_to_hub (bool, 選填, 預設為 False) — 是否在儲存後將您的模型推送到 Hugging Face 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 上的提交網址,否則為 None

將權重儲存於本機目錄。

PyTorch

class huggingface_hub.PyTorchModelHubMixin

< >

( *args **kwargs )

ModelHubMixin 的實作,旨在為 PyTorch 模型提供 Hugging Face 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.machinelearning.tw/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: str | None = 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, 選填) — 下載儲存庫檔案時所使用的版本(revision)。請參閱 snapshot_download 的說明文件。

從 Hub 或本地目錄載入預訓練的 fastai 模型。

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 )

參數

  • learner (Learner) — 您想要推送到 Hub 的 *fastai.Learner*。
  • repo_id (str) — 您模型在 Hub 上的儲存庫識別碼,格式為「命名空間/儲存庫名稱」。命名空間可以是您的個人帳戶,或是您擁有寫入權限的組織(例如:‘stanfordnlp/stanza-de’)。
  • commit_message (str, 選填) — 推送時的提交訊息。預設為 "add model"
  • private (bool, 選填) — 是否將建立的儲存庫設為私有。若為 None(預設值),則會預設為公開,除非該組織的預設設定為私有。
  • token (str, 選填) — 用於遠端檔案 HTTP 持有者授權(bearer authorization)的 Hugging Face 帳戶權杖(token)。若為 None,將會透過提示要求輸入權杖。
  • config (dict, 選填) — 與模型權重一同儲存的設定物件。
  • branch (str, 選填) — 要推送模型的 Git 分支。預設為儲存庫中指定的預設分支,通常為 “main”
  • create_pr (boolean, 選填) — 是否針對該提交(commit)從 branch 建立提取請求(Pull Request)。預設為 False
  • api_endpoint (str, 選填) — 將模型推送到 hub 時使用的 API 端點。
  • allow_patterns (list[str]str, 選填) — 若有提供,則僅會推送符合至少一個樣式的檔案。
  • ignore_patterns (list[str]str, 選填) — 若有提供,則不會推送符合任何樣式的檔案。
  • delete_patterns (list[str]str, 選填) — 若有提供,則符合任何樣式的遠端檔案將會從儲存庫中刪除。

將 learner 檢查點(checkpoint)檔案上傳至 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.