huggingface-cli 是 Hugging Face 官方提供的命令行工具,自带完善的下载功能。
安装依赖
pip install -U huggingface_hub
设置环境变量
linux
# 建议将上面这一行写入 ~/.bashrc。若没有写入,则每次下载时都需要先输入该命令
export HF_ENDPOINT=https://hf-mirror.com
Windows Powershell
$env:HF_ENDPOINT = "https://hf-mirror.com" # 暂时不知如何使用
下载模型样例
使用命令行下载
下载全部文件添加--resume-download
参数,此时将保存至/root/.cache/.../
文件夹中
huggingface-cli download --resume-download meta-llama/Llama-2-13b-chat-hf
下载全部文件并保存到指定位置时,添加--local-dir
参数,此时将保存至./Llama-2-13b-chat-hf/
中
huggingface-cli download --resume-download meta-llama/Llama-2-13b-chat-hf --local-dir Llama-2-13b-chat-hf
下载多个文件时,再添加具体文件名即可
huggingface-cli download meta-llama/Llama-2-13b-chat-hf config.json model-00001-of-00003.safetensors --local-dir Llama-2-13b-chat-hf
下载多个文件并排除一些文件可使用--include
和--exclude
命令
huggingface-cli download meta-llama/Llama-2-13b-chat-hf --include "*.safetensors" --exclude "*.bin"
需要 huggingface token 时 (Gated Repo),添加--token
参数
huggingface-cli download meta-llama/Llama-2-13b-chat-hf --include "*.safetensors" --exclude "*.bin" --token hf_****
使用python脚本下载
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
os.environ["HF_ENDPOINT"] = "https://hf-mirror.com" # 设置为hf的国内镜像网站
from huggingface_hub import snapshot_download
model_name = "meta-llama/Llama-2-13b-chat-hf"
# while True 是为了防止断联
while True:
try:
snapshot_download(
repo_id=model_name,
local_dir_use_symlinks=True, # 在local-dir指定的目录中都是一些“链接文件”
ignore_patterns=["*.bin"], # 忽略下载哪些文件
local_dir=model_name,
token="*************", # huggingface的token
resume_download=True
)
break
except:
pass
下载数据集
将wikitext
数据集下载到本地wikitext
文件中,并取消软连接。
huggingface-cli download --repo-type dataset --resume-download wikitext --local-dir wikitext --local-dir-use-symlinks False