skip to content

With huggingface_hub, when do you use hf_hub_download versus snapshot_download, and how do you avoid pulling every weight format in a repo?

level: middleimportance: should knowfreq 16%

answer

  1. one file or a whole revision
  2. both write into the same cache
  3. allow_patterns and ignore_patterns globs
  4. a star also crosses folder boundaries
  5. hf download --include and --exclude

basics

~20 s

hf_hub_download fetches one named file; snapshot_download fetches a whole revision of a repo. Both write into the same cache and return local paths. Filter a snapshot with allow_patterns and ignore_patterns so only the safetensors weights and configs are pulled.

solid answer

~40 s

`hf_hub_download(repo_id, filename, revision=...)` downloads one file and returns its path in the cache, which suits a single `config.json` or one GGUF file out of a repo of variants. `snapshot_download(repo_id, revision=...)` downloads every file of that revision concurrently and returns the snapshot folder, which is what a loader expecting a directory needs. Older repos often store the same weights several times (`pytorch_model.bin`, `model.safetensors`, `tf_model.h5`, `flax_model.msgpack`, an `onnx/` folder), so pass `allow_patterns=["*.json", "*.safetensors"]` and add `ignore_patterns` where needed. Patterns are case-sensitive `fnmatch` globs, `*` also crosses `/`, and the ignore list is applied after the allow list. Transformers v5 saves only safetensors, so new repos duplicate less. From the shell, `hf download --include ... --exclude ...` does the same; `huggingface-cli` was removed in huggingface_hub v1.0.

code

python · 16 lines
python
from huggingface_hub import hf_hub_download, snapshot_download

REPO = "your-org/your-model"
SHA = "<full 40-character commit hash>"  # the pinned commit

# One file: returns the cached file's path
config_path = hf_hub_download(REPO, "config.json", revision=SHA)

# Whole revision, filtered to safetensors weights and JSON files
model_dir = snapshot_download(
    REPO,
    revision=SHA,
    allow_patterns=["*.json", "*.safetensors"],
    ignore_patterns=["onnx/*"],  # '*' crosses '/', so this drops the ONNX export's JSON
)
print(model_dir)  # .../models--your-org--your-model/snapshots/<commit>

go deeper

for a junior

Recall that hf_hub_download fetches one file and snapshot_download fetches a whole revision, and that both return paths into the local cache.

for a middle

Explain allow_patterns and ignore_patterns precisely: fnmatch globs, case-sensitive, a star that crosses folders, and the ignore list winning.

for a senior

Cut download time and disk by filtering duplicate weight formats, check the result with a dry run, and make sure tokenizer and config files survive the filter before going offline.

for a principal

Set a team convention for how models are fetched: one filtered, pinned snapshot per model version, the cache versus plain folders, and which scripts must move off removed APIs.

## Two functions, one cache `huggingface_hub` offers two download functions. Both store files in the same local cache, keyed by repo and commit, so a file fetched by one is reused by the other. | | `hf_hub_download` | `snapshot_download` | |---|---|---| | Fetches | One file, named by `filename` | Every file at a revision, optionally filtered | | Returns | The path of that file | The path of the snapshot folder | | Concurrency | One file | Parallel downloads (`max_workers`, 8 by default) | | Typical use | A config, a single GGUF quantization, one shard | A model directory to hand to a loader, or an offline warm-up | Both take `revision`, `repo_type` (`"model"` by default, or `"dataset"` / `"space"`), `token`, `cache_dir` and `local_dir`. `from_pretrained` in Transformers calls into the same machinery, which is why a model loaded once is found in the cache next time. ## Why a whole snapshot can be wasteful Many older repos carry one set of weights in several formats. The `huggingface_hub` guide's dry-run of a classic small text-generation repo lists 26 files, of which 11 would need downloading, totalling 5.6G: `model.safetensors`, `pytorch_model.bin`, `tf_model.h5`, `flax_model.msgpack`, `rust_model.ot`, three TFLite files and several ONNX exports. A PyTorch job needs one of those. Transformers v5 is PyTorch-only and always saves safetensors (the `safe_serialization` switch was removed), so repos written by current tooling carry less duplication, but the old ones are still on the Hub. Why the pickle-based formats are risky to load is a supply-chain topic; here the point is bytes and time. ## How the patterns match `allow_patterns` and `ignore_patterns` each take one pattern or a list. - Matching uses Python's **`fnmatch.fnmatchcase`**: glob patterns, not regular expressions, and **case-sensitive** on every platform. - **`*` crosses `/`**, unlike a shell glob, so `"*.json"` also matches `onnx/config.json`, and `"data/*.json"` matches files in nested subfolders of `data/`. - A pattern ending in `/`, such as `"onnx/"`, matches everything under that folder. - A file must match at least one allow pattern (when given) and **no** ignore pattern, so the ignore list wins. - Do not forget the files your loader needs besides weights: tokenizer files such as `tokenizer.json`, `tokenizer.model` or `merges.txt` are easy to filter out by accident. For a repo that ships one GGUF file per quantization, either name the one file to `hf_hub_download` or pass a pattern that matches only that file to `snapshot_download`; what each quantization label means is a separate subject. ## Picking the call in practice 1. **One known file** (a config, one shard, one GGUF quantization): `hf_hub_download`, which costs one request and one file of disk. 2. **A loadable model directory**: `snapshot_download` with `allow_patterns` naming the weight format your framework reads plus every config and tokenizer file it opens. 3. **A shell step in CI or a Dockerfile**: `hf download` with `--revision`, `--include` and `--exclude`, which calls the same two functions and prints the resulting path. 4. **Many files loaded separately by your own code**: resolve the revision to a commit first, so every call lands on the same commit even if the repo is updated mid-run. ## Look before you download - `dry_run=True` on either function returns what would be fetched, with file sizes and whether each file is already cached, without downloading. - `hf download <repo> --dry-run` prints the same as a table, and accepts `--include` / `--exclude` patterns that behave like the Python arguments. ## Cache paths versus `local_dir` 1. **Default (cache):** files land under `HF_HUB_CACHE`, and the returned path points at a snapshot entry that links to a shared blob. Do not edit it in place; you would corrupt the cache for every revision sharing that blob. 2. **`local_dir=`:** files are placed in a plain folder with the repo's structure, plus a `.cache/huggingface/` metadata folder that lets a later call skip unchanged files. Use it when another tool expects a normal directory. ## Release notes that break old scripts - `huggingface_hub` v1.0 removed `resume_download`, `force_filename` and `local_dir_use_symlinks` from both download functions, removed the `huggingface-cli` command in favour of `hf`, and dropped `hf_transfer` support: `HF_HUB_ENABLE_HF_TRANSFER` is ignored, and `HF_XET_HIGH_PERFORMANCE` is the replacement for maximum throughput. - `use_auth_token` was removed from `huggingface_hub` in v1.0, and Transformers v5 replaced it with `token` as well. - Transformers v5 removed `safe_serialization` from `save_pretrained` and `push_to_hub`; weights are always written as safetensors.

  • Your filtered snapshot_download loads fine online, but an offline worker fails to build the tokenizer. What happened?
    The patterns probably excluded a tokenizer file the loader needs, such as `tokenizer.model` or `merges.txt`, because only `*.json` and `*.safetensors` were allowed. Online, the loader quietly fetched the missing file; offline it cannot. Run the download with `dry_run=True`, check the list against what the loader reads, and add the missing names to `allow_patterns`.
  • When would you pass local_dir instead of relying on the cache?
    When another tool needs a plain folder with the repo's file layout, for example to copy into an image or hand to a non-Python runtime. `local_dir` writes real files there plus a `.cache/huggingface/` metadata folder so repeated calls skip unchanged files. Otherwise the cache is preferable: it deduplicates across revisions and is shared by every Hugging Face library.

  • snapshot_download always fetches every file; filtering means calling hf_hub_download in a loop.
  • In allow_patterns, *.json only matches JSON files at the repo root.
  • Patterns are regular expressions, so you write .*\.safetensors to match weights.
  • Editing a file at the path hf_hub_download returned is a safe local patch.
  • huggingface-cli download is still the command to use in setup scripts.

Assumes Transformers v5 with huggingface_hub 2.1: huggingface-cli and several download arguments were removed in huggingface_hub v1.0, and Transformers v5 always saves safetensors.