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 文件和资产之间是有区别的。来自 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, optional) — 要缓存的缓存目录。默认为默认的 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(...),
        ...
    ],
)

您还可以直接从 huggingface-cli 使用以下命令打印详细报告

> huggingface-cli scan-cache
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 等于所有仓库大小(仅限 blobs)的总和。但是,如果某些缓存仓库已损坏,则其大小将不被考虑在内。

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。

返回值

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: 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 上的仓库完全相同的树状结构,但仅包含符号链接。一个修订版本可以被 1 个或多个 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 上更新