Hub Python 庫文件

快取系統參考

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

快取系統參考

在 v0.8.0 版本中,快取系統進行了更新,使其成為依賴 Hub 的庫共享的中央快取系統。閱讀快取系統指南以詳細瞭解 HF 的快取。

輔助函式

try_to_load_from_cache

huggingface_hub.try_to_load_from_cache

< >

( repo_id: str filename: str cache_dir: typing.Union[str, pathlib.Path, NoneType] = None revision: typing.Optional[str] = None repo_type: typing.Optional[str] = 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

探索快取,以查詢給定修訂版本的最新快取檔案(如果找到)。

如果檔案未被快取,此函式將不會引發任何異常。

示例

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: typing.Union[str, pathlib.Path, NoneType] = 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 檔案快取方式是 git 感知的,完全由 huggingface_hub 管理。而所有其他由下游庫快取的檔案都被視為“資產”(從外部源下載的檔案、從 .tar 存檔中解壓的檔案、為訓練預處理的檔案等)。

一旦生成資料夾路徑,即可保證其存在並且是一個目錄。路徑基於三個層級的深度:庫名稱、名稱空間和子資料夾。這三個層級提供了靈活性,同時允許 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: typing.Union[str, pathlib.Path, NoneType] = None )

引數

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

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

使用 scan_cache_dir 來以程式設計方式掃描您的快取系統。快取將逐個倉庫進行掃描。如果一個倉庫損壞,將內部引發一個 ~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() 構建並返回,並且是不可變的。

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 不是為了修改而設計的,但它允許在實際執行刪除之前進行試執行。

export_as_table

< >

( verbosity: int = 0 ) str

引數

  • verbosity (int, optional) — 詳細程度級別。預設為 0。

返回

字串

表格字串。

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

< >

( )

(property) blob 檔案大小的可讀字串表示。

例如:“42.2K”。

refs

< >

( )

(property) 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,則被視為分離。例如:{"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

< >

( )

(property) blob 檔案大小的可讀字串表示。

例如:“42.2K”。

nb_files

< >

( )

(property) 版本中的檔案總數。

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 的符號連結。
  • blob_path (Path) — blob 檔案路徑。這等同於 file_path.resolve()
  • size_on_disk (int) — blob 檔案在磁碟上的大小(位元組)。
  • blob_last_accessed (float) — blob 檔案上次被訪問的時間戳(來自任何修訂版本)。
  • blob_last_modified (float) — blob 檔案上次修改/建立的時間戳。

儲存單個快取檔案資訊的凍結資料結構。

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

size_on_disk_str

< >

( )

(property) 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]) — 要刪除的引用檔案路徑集。
  • repos (frozenset[Path]) — 要刪除的整個倉庫路徑集。
  • snapshots (frozenset[Path]) — 要刪除的快照集(符號連結目錄)。

儲存用於刪除快取修訂版的策略的凍結資料結構。

此物件不用於以程式設計方式例項化,而是由 delete_revisions() 返回。請參閱文件中的用法示例。

expected_freed_size_str

< >

( )

(property) 預計將釋放的空間的可讀字串。

例如:“42.2K”。

異常

CorruptedCacheException

class huggingface_hub.CorruptedCacheException

< >

( )

Huggingface 快取系統中任何意外結構引發的異常。

在 GitHub 上更新

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