Hub Python 函式庫文件

快取系統參考

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

快取系統參考

快取系統在 v0.8.0 中進行了更新,成為所有依賴 Hub 的函式庫所共用的核心快取系統。請閱讀快取系統指南,以獲取關於 HF 快取機制的詳細說明。

輔助函式 (Helpers)

try_to_load_from_cache

huggingface_hub.try_to_load_from_cache

< >

( repo_id: str filename: str cache_dir: str | pathlib.Path | None = None revision: str | None = None repo_type: str | None = None ) Optional[str]_CACHED_NO_EXIST

參數

  • cache_dir (stros.PathLike) — 存放快取檔案的資料夾。
  • repo_id (str) — huggingface.co 上儲存庫的 ID。
  • filename (str) — 要在 repo_id 中搜尋的檔案名稱。
  • revision (str, 選填) — 要使用的特定模型版本。若未提供且未指定 commit_hash,將預設為 "main"
  • repo_type (str, 選填) — 儲存庫的類型。將預設為 "model"

返回

Optional[str]_CACHED_NO_EXIST

若檔案未被快取,將回傳 None。否則

  • 若在快取中找到檔案,則回傳該快取檔案的確切路徑。
  • 若給定提交雜湊值 (commit hash) 對應的檔案不存在,且此事實已被快取,則回傳特殊值 _CACHED_NO_EXIST

瀏覽快取以在找到時回傳指定版本 (revision) 的最新快取檔案。

若檔案未被快取,此函式不會引發任何例外。

範例

from huggingface_hub import try_to_load_from_cache, _CACHED_NO_EXIST

filepath = try_to_load_from_cache()
if isinstance(filepath, str):
    # file exists and is cached
    ...
elif filepath is _CACHED_NO_EXIST:
    # non-existence of file is cached
    ...
else:
    # file is not cached
    ...

cached_assets_path

huggingface_hub.cached_assets_path

< >

( library_name: str namespace: str = 'default' subfolder: str = 'default' assets_dir: str | pathlib.Path | None = None )

參數

  • library_name (str) — 管理此快取資料夾的函式庫名稱。範例:"dataset"
  • namespace (str, 選填,預設為 “default”) — 資料所屬的命名空間。範例:"SQuAD"
  • subfolder (str, 選填,預設為 “default”) — 儲存資料的子資料夾。範例:extracted
  • assets_dir (str, Path, 選填) — 快取資產的資料夾路徑。這必須與 Hub 檔案快取的位置不同。若未提供,預設為 HF_HOME / "assets"。亦可透過 HF_ASSETS_CACHE 環境變數設定。

回傳一個用於快取任意檔案的資料夾路徑。

huggingface_hub 提供了一個標準化的資料夾路徑來儲存資產。這是將快取整合到下游函式庫的推薦做法,因為它能受惠於內建工具,從而正確地掃描並刪除快取。

從 Hub 快取的檔案與「資產」(assets) 之間有區別。來自 Hub 的檔案以 Git 感知的方式進行快取,並完全由 huggingface_hub 管理。詳見相關文件。下游函式庫快取的所有其他檔案都被視為「資產」(從外部來源下載的檔案、從 .tar 歸檔中提取的檔案、預處理後的訓練資料等)。

一旦產生資料夾路徑,該資料夾保證會存在且為目錄。路徑基於 3 個層級:函式庫名稱、命名空間和子資料夾。這 3 個層級在提供彈性的同時,也允許 huggingface_hub 在掃描/刪除資產快取的部分時能識別這些資料夾。在函式庫內部,通常預期所有命名空間會共享相同的一組子資料夾名稱,但這並非強制規則。下游函式庫可以完全掌控在其快取中採用的檔案結構。命名空間和子資料夾是選填的(預設為 "default/" 子資料夾),但函式庫名稱是強制要求的,因為我們希望每個下游函式庫都能管理自己的快取。

預期目錄樹

    assets/
    └── datasets/
    │   ├── SQuAD/
    │   │   ├── downloaded/
    │   │   ├── extracted/
    │   │   └── processed/
    │   ├── Helsinki-NLP--tatoeba_mt/
    │       ├── downloaded/
    │       ├── extracted/
    │       └── processed/
    └── transformers/
        ├── default/
        │   ├── something/
        ├── bert-base-cased/
        │   ├── default/
        │   └── training/
    hub/
    └── models--julien-c--EsperBERTo-small/
        ├── blobs/
        │   ├── (...)
        │   ├── (...)
        ├── refs/
        │   └── (...)
        └── [ 128]  snapshots/
            ├── 2439f60ef33a0d46d85da5001d52aeda5b00ce9f/
            │   ├── (...)
            └── bbc77c8132af1cc5cf678da3f1ddf2de43606d48/
                └── (...)

範例

>>> from huggingface_hub import cached_assets_path

>>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="download")
PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/download')

>>> cached_assets_path(library_name="datasets", namespace="SQuAD", subfolder="extracted")
PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/SQuAD/extracted')

>>> cached_assets_path(library_name="datasets", namespace="Helsinki-NLP/tatoeba_mt")
PosixPath('/home/wauplin/.cache/huggingface/extra/datasets/Helsinki-NLP--tatoeba_mt/default')

>>> cached_assets_path(library_name="datasets", assets_dir="/tmp/tmp123456")
PosixPath('/tmp/tmp123456/datasets/default/default')

scan_cache_dir

huggingface_hub.scan_cache_dir

< >

( cache_dir: str | pathlib.Path | None = None )

參數

  • cache_dir (strPath, 選填) — 要掃描的快取目錄。預設為預設的 HF 快取目錄。

掃描整個 HF 快取系統並回傳一個 ~HFCacheInfo 結構。

使用 scan_cache_dir 以程式化方式掃描您的快取系統。快取將逐個儲存庫 (repo) 進行掃描。若某個儲存庫損毀,內部會拋出 ~CorruptedCacheException,但該例外會被捕捉並回傳至 ~HFCacheInfo 結構中。只有有效的儲存庫會得到正確的報告。

>>> from huggingface_hub import scan_cache_dir

>>> hf_cache_info = scan_cache_dir()
HFCacheInfo(
    size_on_disk=3398085269,
    repos=frozenset({
        CachedRepoInfo(
            repo_id='t5-small',
            repo_type='model',
            repo_path=PosixPath(...),
            size_on_disk=970726914,
            nb_files=11,
            revisions=frozenset({
                CachedRevisionInfo(
                    commit_hash='d78aea13fa7ecd06c29e3e46195d6341255065d5',
                    size_on_disk=970726339,
                    snapshot_path=PosixPath(...),
                    files=frozenset({
                        CachedFileInfo(
                            file_name='config.json',
                            size_on_disk=1197
                            file_path=PosixPath(...),
                            blob_path=PosixPath(...),
                        ),
                        CachedFileInfo(...),
                        ...
                    }),
                ),
                CachedRevisionInfo(...),
                ...
            }),
        ),
        CachedRepoInfo(...),
        ...
    }),
    warnings=[
        CorruptedCacheException("Snapshots dir doesn't exist in cached repo: ..."),
        CorruptedCacheException(...),
        ...
    ],
)

您也可以透過 hf 指令列直接列印詳細報告:

> hf cache ls
ID                          SIZE     LAST_ACCESSED LAST_MODIFIED REFS
--------------------------- -------- ------------- ------------- -----------
dataset/nyu-mll/glue          157.4M 2 days ago    2 days ago    main script
model/LiquidAI/LFM2-VL-1.6B     3.2G 4 days ago    4 days ago    main
model/microsoft/UserLM-8b      32.1G 4 days ago    4 days ago    main

Done in 0.0s. Scanned 6 repo(s) for a total of 3.4G.
Got 1 warning(s) while scanning. Use -vvv to print details.

引發

CacheNotFound 若快取目錄不存在。

ValueError 若快取目錄是檔案而非目錄。

回傳:一個 ~HFCacheInfo 物件。

資料結構

所有結構皆由 scan_cache_dir() 建立並回傳,且為不可變 (immutable)。

HFCacheInfo

class huggingface_hub.HFCacheInfo

< >

( size_on_disk: int repos: frozenset warnings: list )

參數

  • size_on_disk (int) — 快取系統中所有有效儲存庫大小的總和。
  • repos (frozenset[CachedRepoInfo]) — ~CachedRepoInfo 的集合,描述掃描期間在快取系統中發現的所有有效快取儲存庫。
  • warnings (list[CorruptedCacheException]) — 掃描快取時發生的 ~CorruptedCacheException 列表。這些例外被捕捉以確保掃描可以繼續進行。損毀的儲存庫將從掃描中略過。

持有關於整個快取系統資訊的固定資料結構。

此資料結構由 scan_cache_dir() 回傳且為不可變。

此處的 size_on_disk 等於所有儲存庫大小(僅 Blob)的總和。然而,若某些快取的儲存庫已損毀,其大小將不會被計入。

delete_revisions

< >

( *revisions: str )

準備刪除一個或多個本地快取版本的策略。

輸入的版本可以是任何版本雜湊值。若在本地快取中未找到該版本雜湊值,則會發出警告,但不會引發錯誤。由於雜湊值在所有儲存庫中皆為唯一,因此這些版本可以來自不同的快取儲存庫。

範例

>>> from huggingface_hub import scan_cache_dir
>>> cache_info = scan_cache_dir()
>>> delete_strategy = cache_info.delete_revisions(
...     "81fd1d6e7847c99f5862c9fb81387956d99ec7aa"
... )
>>> print(f"Will free {delete_strategy.expected_freed_size_str}.")
Will free 7.9K.
>>> delete_strategy.execute()
Cache deletion done. Saved 7.9K.
>>> from huggingface_hub import scan_cache_dir
>>> scan_cache_dir().delete_revisions(
...     "81fd1d6e7847c99f5862c9fb81387956d99ec7aa",
...     "e2983b237dccf3ab4937c97fa717319a9ca1a96d",
...     "6c0e6080953db56375760c0471a8c5f2929baf11",
... ).execute()
Cache deletion done. Saved 8.6G.

delete_revisions 回傳一個需要被執行的 DeleteCacheStrategy 物件。該 DeleteCacheStrategy 不應被修改,但允許在實際執行刪除之前進行預覽 (dry run)。

export_as_table

< >

( verbosity: int = 0 ) str

參數

  • verbosity (int, 選填) — 詳細程度等級。預設為 0。

返回

str

作為字串的表格。

HFCacheInfo 物件產生一個表格。

傳入 verbosity=0 以取得一個每個儲存庫佔一行、包含「repo_id」、「repo_type」、「size_on_disk」、「nb_files」、「last_accessed」、「last_modified」、「refs」、「local_path」欄位的表格。

傳入 verbosity=1 以取得一個每個儲存庫版本佔一行(因此單一儲存庫可能會出現多行)、包含「repo_id」、「repo_type」、「revision」、「size_on_disk」、「nb_files」、「last_modified」、「refs」、「local_path」欄位的表格。

範例

>>> from huggingface_hub.utils import scan_cache_dir

>>> hf_cache_info = scan_cache_dir()
HFCacheInfo(...)

>>> print(hf_cache_info.export_as_table())
REPO ID                                             REPO TYPE SIZE ON DISK NB FILES LAST_ACCESSED LAST_MODIFIED REFS LOCAL PATH
--------------------------------------------------- --------- ------------ -------- ------------- ------------- ---- --------------------------------------------------------------------------------------------------
roberta-base                                        model             2.7M        5 1 day ago     1 week ago    main ~/.cache/huggingface/hub/models--roberta-base
suno/bark                                           model             8.8K        1 1 week ago    1 week ago    main ~/.cache/huggingface/hub/models--suno--bark
t5-base                                             model           893.8M        4 4 days ago    7 months ago  main ~/.cache/huggingface/hub/models--t5-base
t5-large                                            model             3.0G        4 5 weeks ago   5 months ago  main ~/.cache/huggingface/hub/models--t5-large

>>> print(hf_cache_info.export_as_table(verbosity=1))
REPO ID                                             REPO TYPE REVISION                                 SIZE ON DISK NB FILES LAST_MODIFIED REFS LOCAL PATH
--------------------------------------------------- --------- ---------------------------------------- ------------ -------- ------------- ---- -----------------------------------------------------------------------------------------------------------------------------------------------------
roberta-base                                        model     e2da8e2f811d1448a5b465c236feacd80ffbac7b         2.7M        5 1 week ago    main ~/.cache/huggingface/hub/models--roberta-base/snapshots/e2da8e2f811d1448a5b465c236feacd80ffbac7b
suno/bark                                           model     70a8a7d34168586dc5d028fa9666aceade177992         8.8K        1 1 week ago    main ~/.cache/huggingface/hub/models--suno--bark/snapshots/70a8a7d34168586dc5d028fa9666aceade177992
t5-base                                             model     a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1       893.8M        4 7 months ago  main ~/.cache/huggingface/hub/models--t5-base/snapshots/a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1
t5-large                                            model     150ebc2c4b72291e770f58e6057481c8d2ed331a         3.0G        4 5 months ago  main ~/.cache/huggingface/hub/models--t5-large/snapshots/150ebc2c4b72291e770f58e6057481c8d2ed331a

CachedRepoInfo

class huggingface_hub.CachedRepoInfo

< >

( repo_id: str repo_type: typing.Literal['model', 'dataset', 'space'] repo_path: Path size_on_disk: int nb_files: int revisions: frozenset last_accessed: float last_modified: float )

參數

  • repo_id (str) — Hub 上儲存庫的儲存庫 ID。範例:"google/fleurs"
  • repo_type (Literal["dataset", "model", "space"]) — 快取儲存庫的類型。
  • repo_path (Path) — 快取儲存庫的本地路徑。
  • size_on_disk (int) — 快取儲存庫中 Blob 檔案大小的總和。
  • nb_files (int) — 快取儲存庫中 Blob 檔案的總數。
  • revisions (frozenset[CachedRevisionInfo]) — ~CachedRevisionInfo 的集合,描述儲存庫中快取的所有版本。
  • last_accessed (float) — 儲存庫 Blob 檔案上次被存取的時間戳記。
  • last_modified (float) — 儲存庫 Blob 檔案上次被修改/建立的時間戳記。

持有關於快取儲存庫資訊的固定資料結構。

由於檔案重複,size_on_disk 不一定等於所有版本大小的總和。此外,僅考慮 Blob,不考慮資料夾和符號連結(大小可忽略不計)。

last_accessedlast_modified 的可靠性取決於您使用的作業系統。更多詳細資訊請參閱 Python 文件

size_on_disk_str

< >

( )

(屬性) Blob 檔案大小總和,以人類可讀的字串表示。

範例:「42.2K」。

refs

< >

( )

(屬性) refs 與版本資料結構之間的對應。

CachedRevisionInfo

class huggingface_hub.CachedRevisionInfo

< >

( commit_hash: str snapshot_path: Path size_on_disk: int files: frozenset refs: frozenset last_modified: float )

參數

  • commit_hash (str) — 版本的雜湊值(唯一)。範例:"9338f7b671827df886678df2bdd7cc7b4f36dffd"
  • snapshot_path (Path) — snapshots 資料夾中版本目錄的路徑。它包含與 Hub 上儲存庫完全相同的樹狀結構。
  • files — (frozenset[CachedFileInfo]): ~CachedFileInfo 的集合,描述快照中包含的所有檔案。
  • refs (frozenset[str]) — 指向此版本的 refs 集合。若版本沒有 refs,則被視為「分離」(detached)。範例:{"main", "2.4.0"}{"refs/pr/1"}
  • size_on_disk (int) — 該版本以符號連結關聯的 Blob 檔案大小總和。
  • last_modified (float) — 版本上次被建立/修改的時間戳記。

持有關於版本資訊的固定資料結構。

版本對應於 snapshots 資料夾中的一個資料夾,並且填充了與 Hub 上儲存庫完全相同的樹狀結構,但僅包含符號連結。一個版本可以由一個或多個 refs 參考,也可以是「分離的」(無 refs)。

因為 Blob 檔案是在各個版本間共享的,所以無法在單一版本上正確判斷 last_accessed

由於可能存在重複檔案,size_on_disk 不一定等於所有檔案大小的總和。此外,僅考慮 Blob,不考慮資料夾和符號連結(大小可忽略不計)。

size_on_disk_str

< >

( )

(屬性) Blob 檔案大小總和,以人類可讀的字串表示。

範例:「42.2K」。

nb_files

< >

( )

(屬性) 版本中的檔案總數。

CachedFileInfo

class huggingface_hub.CachedFileInfo

< >

( file_name: str file_path: Path blob_path: Path size_on_disk: int blob_last_accessed: float blob_last_modified: float )

參數

  • file_name (str) — 檔案名稱。例如:config.json
  • file_path (Path) — 位於 snapshots 目錄下的檔案路徑。該檔案路徑是一個指向 blobs 資料夾中 blob 的符號連結 (symlink)。
  • blob_path (Path) — Blob 檔案的路徑。這等同於 file_path.resolve()
  • size_on_disk (int) — Blob 檔案的大小(以位元組為單位)。
  • blob_last_accessed (float) — Blob 檔案上次被存取的時間戳記(來自任何版本)。
  • blob_last_modified (float) — Blob 檔案上次被修改/建立的時間戳記。

用於保存單一快取檔案資訊的凍結 (frozen) 資料結構。

blob_last_accessedblob_last_modified 的可靠性可能取決於您使用的作業系統。詳情請參閱 Python 文件

size_on_disk_str

< >

( )

(屬性) Blob 檔案大小的人類可讀字串。

範例:「42.2K」。

DeleteCacheStrategy

class huggingface_hub.DeleteCacheStrategy

< >

( expected_freed_size: int blobs: frozenset refs: frozenset repos: frozenset snapshots: frozenset )

參數

  • expected_freed_size (float) — 執行策略後預計釋放的大小。
  • blobs (frozenset[Path]) — 待刪除的 blob 檔案路徑集合。
  • refs (frozenset[Path]) — 待刪除的參照 (reference) 檔案路徑集合。
  • repos (frozenset[Path]) — 待刪除的整個儲存庫路徑集合。
  • snapshots (frozenset[Path]) — 待刪除的快照集合(符號連結目錄)。

用於保存刪除快取版本策略的凍結 (frozen) 資料結構。

此物件並非設計用於以程式方式實例化,而是由 delete_revisions() 回傳。使用範例請參閱說明文件。

expected_freed_size_str

< >

( )

(屬性) 預計釋放的大小,以人類可讀字串表示。

範例:「42.2K」。

例外狀況 (Exceptions)

CorruptedCacheException

class huggingface_hub.CorruptedCacheException

< >

( )

Huggingface 快取系統中出現意外結構時引發的例外狀況。

在 GitHub 上更新

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