如果您希望在本地使用 Hugging Face 上的预训练模型,但遇到下载缓慢、中断或无法获取完整文件等问题,则可能是由于网络连接不稳定、未配置镜像源或工具选择不当所致。以下是多种切实可行的模型文件下载方法:
一、使用 Hugging Face CLI 工具下载
该方法是官方推荐的命令行方式,支持断点续传、指定目录、跳过已存在文件等功能,适用于大多数用户且兼容性高。
1、在终端中执行命令安装 huggingface_hub 工具:pip install huggingface_hub
2、设置国内镜像加速(关键提速步骤):Linux/macOS 用户在 ~/.bashrc 中添加:export HF_ENDPOINT=https://hf-mirror.comWindows PowerShell 用户执行:$env:HF_ENDPOINT="https://hf-mirror.com"
3、执行模型下载命令,例如下载 Qwen2-7B-Instruct:huggingface-cli download --resume-download --local-dir-use-symlinks False Qwen/Qwen2-7B-Instruct --local-dir ./models/qwen2-7b
4、如需下载私有模型,先执行 huggingface-cli login 并粘贴具有 Read 权限的 Access Token。
二、通过 Python 代码调用 snapshot_download
该方法适合集成到脚本中,可精确控制下载行为,支持强制重下、忽略特定文件、限制下载大小等高级选项。
1、确保已安装 transformers 和 huggingface_hub:pip install transformers huggingface_hub
2、运行以下 Python 脚本:from huggingface_hub import snapshot_downloadsnapshot_download(repo_id="bert-base-chinese", local_dir="./models/bert_chinese", force_download=True)
3、如需仅下载部分文件,可传入 allow_patterns 参数,例如只下载 pytorch_model.bin 和 config.json:allow_patterns=["pytorch_model.bin", "config.json"]
4、若模型含 safetensors 格式且想优先获取,可在 allow_patterns 中显式指定:allow_patterns=["*.safetensors", "config.json"]
三、使用 Git LFS 克隆仓库
此方式保留完整 Git 历史与元数据,适合需要复现训练过程或验证文件完整性的开发者,但默认会拉取全部框架版本文件。
1、安装 Git 和 Git LFS:macOS 执行 brew install git-lfs;Windows 用户从 git-lfs.github.com 下载安装器
2、初始化 LFS 并克隆仓库:git lfs installgit clone https://huggingface.co/decapoda-research/llama-7b-hf
。