【教程】huggingface安装及使用

一、前言

Hugging Face 起初是一个专注于自然语言处理(NLP)和机器学习的开源平台和社区,提供了一系列工具、库和预训练模型,帮助开发者和研究者快速构建、训练和部署 AI 应用。

官方文档:https://huggingface.co/docs/huggingface_hub/guides/cli

二、安装

Ubuntu:

curl -LsSf https://hf.co/cli/install.sh | bash

windows:

powershell -ExecutionPolicy ByPass -c "irm https://hf.co/cli/install.ps1 | iex"

完成后测试

hf --help

平时可能需要下载大文件,这里需要用到git lfs

sudo apt install -y git-lfs
# 测试
git lfs install

三、登录

在官网https://huggingface.co/注册并登录后,获取token

image-20260304155526517

这里建议获取read token,平时很少用到write

回到控制台中,这里以ubuntu为例,hf安装后,目录在~/.hf-cli,其环境中缺少了socks,需要手动安装

~/.hf-cli/venv/bin/python -m pip install --upgrade "http[socks]" socksio

登录

hf auth login

期间会让你输入token,这里直接粘贴即可,控制台不显示
之后询问是否将token保存到git credential helper中,如果已经安装了git credential helper可以接受,否则输入N

如果这里报错:

Error: Invalid user token.

可以在命令前加一个DEBUG

HF_DEBUG=1 hf auth login

此时登录会把报错日志打印到终端

这里我分享一个我遇到的问题,我先在环境变量中配置了国内镜像 https://hf-mirror.com ,导致本地登录时token校验通不过。

添加debug选项得到下面的报错:

Request xx: GET https://hf-mirror.com/api/whoami-v2 (authenticated: True)
Request xx: GET https://huggingface.co/api/whoami-v2 (authenticated: False)

可以看到请求到国内镜像是通过的,但是转发到huggingface上token丢失了,因此只需要在登录时指定huggingface官方站链接,避免二次转发即可。

HF_ENDPOINT=https://huggingface.co hf auth login

四、下载

4.1 配置

下载前需要做一个镜像配置,如果你肉身在国外可跳过此步

export HF_ENDPOINT=https://hf-mirror.com

4.2 单个文件

hf download <repo_id> <path/in/repo> --repo-type <dataset|space|model> --local-dir <目标目录>

hf download a/b c/d.json --repo-type dataset --local-dir ~/workspace_act/a

4.2 多个文件

  • 批量下载
# 通过文件过滤的方式
hf download a/b --repo-type dataset \
  --include "c/zs/*" \
  --local-dir ~/workspace_act/a
  • 下载整个仓库
hf download <repo_id> --repo-type <dataset|space|model> --local-dir <目标目录>

如果下载中断,直接在上次执行目录执行相同命令即可断点续传,cache在~/.cache/huggingface,可通过HF_HOME修改。

posted @ 2026-03-04 16:30  小拳头呀  阅读(651)  评论(0)    收藏  举报