How to download model from Hugging Face
Quick answer
Use the
huggingface_hub Python library to download models from Hugging Face Hub. Install it via pip install huggingface_hub, then call hf_hub_download(repo_id, filename) to fetch model files programmatically.PREREQUISITES
Python 3.8+pip install huggingface_hub>=0.14.1Hugging Face account (optional for private models)
Setup
Install the official Hugging Face Hub Python SDK to interact with the model repository. Optionally, set your Hugging Face API token as an environment variable for private model access.
pip install huggingface_hub>=0.14.1 Step by step
Use the hf_hub_download function to download a specific file from a Hugging Face model repository. Provide the repository ID and filename. The function returns the local path to the downloaded file.
from huggingface_hub import hf_hub_download
# Download the PyTorch model file from the 'bert-base-uncased' repo
local_path = hf_hub_download(repo_id="bert-base-uncased", filename="pytorch_model.bin")
print(f"Model downloaded to: {local_path}") output
Model downloaded to: /home/user/.cache/huggingface/hub/models--bert-base-uncased/snapshots/abcdef123456/pytorch_model.bin
Common variations
- Download tokenizer files by specifying their filenames, e.g.,
tokenizer.json. - Use
repo_type="dataset"to download dataset files. - Authenticate with
use_auth_token=Truefor private models. - Use async versions with
asyncioandhuggingface_hubasync API.
from huggingface_hub import hf_hub_download
# Download tokenizer file
local_tokenizer = hf_hub_download(repo_id="bert-base-uncased", filename="tokenizer.json")
# Download private model file with authentication
import os
local_private = hf_hub_download(
repo_id="private-user/private-model",
filename="pytorch_model.bin",
use_auth_token=os.environ["HF_API_TOKEN"]
)
print(f"Tokenizer downloaded to: {local_tokenizer}")
print(f"Private model downloaded to: {local_private}") output
Tokenizer downloaded to: /home/user/.cache/huggingface/hub/models--bert-base-uncased/snapshots/abcdef123456/tokenizer.json Private model downloaded to: /home/user/.cache/huggingface/hub/models--private-user-private-model/snapshots/123456abcdef/pytorch_model.bin
Troubleshooting
- If you get a
RepositoryNotFoundError, verify therepo_idspelling and your access rights. - For authentication errors, ensure your Hugging Face token is valid and set in
HF_API_TOKENenvironment variable. - Check your internet connection if downloads fail or timeout.
- Clear the cache folder
~/.cache/huggingface/hubif corrupted files cause issues.
Key Takeaways
- Use the official
huggingface_hubPython SDK to download models easily. - Set your Hugging Face API token in environment variables for private model access.
- Specify exact filenames when downloading specific model or tokenizer files.
- Handle common errors by verifying repo IDs and authentication tokens.
- Cache is stored locally under
~/.cache/huggingface/hubfor reuse.