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。否則,

  • 如果檔案在快取中找到,則返回快取檔案的確切路徑
  • 如果檔案在給定提交雜湊下不存在且此事實已被快取,則返回特殊值 _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 快取的檔案和資產之間存在區別。來自 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: typing.Union[str, pathlib.Path, NoneType] = None )

引數

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

引發

CacheNotFoundValueError

  • CacheNotFound — 如果快取目錄不存在。

  • ValueError — 如果快取目錄是檔案而不是目錄。

掃描整個 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 scan
REPO ID                     REPO TYPE SIZE ON DISK NB FILES REFS                LOCAL PATH
--------------------------- --------- ------------ -------- ------------------- -------------------------------------------------------------------------
glue                        dataset         116.3K       15 1.17.0, main, 2.4.0 /Users/lucain/.cache/huggingface/hub/datasets--glue
google/fleurs               dataset          64.9M        6 main, refs/pr/1     /Users/lucain/.cache/huggingface/hub/datasets--google--fleurs
Jean-Baptiste/camembert-ner model           441.0M        7 main                /Users/lucain/.cache/huggingface/hub/models--Jean-Baptiste--camembert-ner
bert-base-cased             model             1.9G       13 main                /Users/lucain/.cache/huggingface/hub/models--bert-base-cased
t5-base                     model            10.1K        3 main                /Users/lucain/.cache/huggingface/hub/models--t5-base
t5-small                    model           970.7M       11 refs/pr/1, main     /Users/lucain/.cache/huggingface/hub/models--t5-small

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.

返回:一個 ~HFCacheInfo 物件。

資料結構

所有結構均由 scan_cache_dir() 構建和返回,且不可變。

HFCacheInfo

class huggingface_hub.HFCacheInfo

< >

( size_on_disk: int repos: typing.FrozenSet[huggingface_hub.utils._cache_manager.CachedRepoInfo] warnings: typing.List[huggingface_hub.errors.CorruptedCacheException] )

引數

  • 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, 可選) — 詳細程度。預設為 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: typing.FrozenSet[huggingface_hub.utils._cache_manager.CachedRevisionInfo] 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: typing.FrozenSet[huggingface_hub.utils._cache_manager.CachedFileInfo] refs: typing.FrozenSet[str] 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

< >

( )

(屬性) 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 的符號連結。
  • 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

< >

( )

(屬性) blob 檔案大小的可讀字串。

示例:“42.2K”。

DeleteCacheStrategy

class huggingface_hub.DeleteCacheStrategy

< >

( expected_freed_size: int blobs: typing.FrozenSet[pathlib.Path] refs: typing.FrozenSet[pathlib.Path] repos: typing.FrozenSet[pathlib.Path] snapshots: typing.FrozenSet[pathlib.Path] )

引數

  • expected_freed_size (float) — 策略執行後預期的釋放大小。
  • blobs (FrozenSet[Path]) — 要刪除的 blob 檔案路徑集合。
  • refs (FrozenSet[Path]) — 要刪除的引用檔案路徑集合。
  • repos (FrozenSet[Path]) — 要刪除的整個倉庫路徑集合。
  • snapshots (FrozenSet[Path]) — 要刪除的快照集合(符號連結目錄)。

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

此物件不應透過程式設計方式例項化,而應由 delete_revisions() 返回。有關使用示例,請參閱文件。

expected_freed_size_str

< >

( )

(屬性) 預期將被釋放的空間大小(人類可讀字串)。

示例:“42.2K”。

異常

CorruptedCacheException

class huggingface_hub.CorruptedCacheException

< >

( )

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

< > 在 GitHub 上更新

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