训练了一个超棒的模型,却不知道如何分享给社区?这篇指南手把手教你把模型上传到 Hugging Face Hub,覆盖 Python API、Git、Web 界面等多种方式,总有一款适合你。
📋 目录
- [前置准备:账号与 Token](#前置准备:账号与 Token "#1-%E5%89%8D%E7%BD%AE%E5%87%86%E5%A4%87%E8%B4%A6%E5%8F%B7%E4%B8%8E-token")
- [方式一:Web 界面上传(最简单)](#方式一:Web 界面上传(最简单) "#2-%E6%96%B9%E5%BC%8F%E4%B8%80web-%E7%95%8C%E9%9D%A2%E4%B8%8A%E4%BC%A0%E6%9C%80%E7%AE%80%E5%8D%95")
- [方式二:Python API 上传(最推荐)](#方式二:Python API 上传(最推荐) "#3-%E6%96%B9%E5%BC%8F%E4%BA%8Cpython-api-%E4%B8%8A%E4%BC%A0%E6%9C%80%E6%8E%A8%E8%8D%90")
- [方式三:Git + Git LFS 上传(适合大模型)](#方式三:Git + Git LFS 上传(适合大模型) "#4-%E6%96%B9%E5%BC%8F%E4%B8%89git--git-lfs-%E4%B8%8A%E4%BC%A0%E9%80%82%E5%90%88%E5%A4%A7%E6%A8%A1%E5%9E%8B")
- 方式四:PyTorchModelHubMixin(自定义模型神器)
- 最佳实践与避坑指南
1. 前置准备:账号与 Token
无论用哪种方式上传,都需要先完成这两步:
1.1 注册 Hugging Face 账号
访问 huggingface.co/join 注册,建议开启两步验证。
1.2 获取 Access Token
进入 Settings → Access Tokens,点击 New token:
| 权限类型 | 说明 |
|---|---|
read |
只能下载模型 |
write |
可以上传模型(推荐选这个) |
fine-grained |
自定义权限 |
复制生成的 token,后续会用到。
1.3 安装依赖
bash
pip install huggingface_hub
然后登录:
bash
huggingface-cli login
# 粘贴你的 token
或者用 Python 代码登录:
python
from huggingface_hub import login
login(token="your_token_here")
2. 方式一:Web 界面上传(最简单)
适合场景:文件数量少、模型不大、想快速体验。
步骤
- 访问 huggingface.co/new 创建新模型仓库
- 填写仓库名(如
my-awesome-model),选择公开/私有 - 进入仓库 → Files and versions → Add file → Upload files
- 拖拽文件或点击上传,填写 commit message
- 点击 Commit changes
⚠️ 注意:Web 界面单个文件限制约 5GB,超大文件请用 Git LFS 或 Python API。
3. 方式二:Python API 上传(最推荐)
huggingface_hub 库提供了最灵活的上传方式,支持断点续传、进度条、批量上传。
3.1 上传单个文件
python
from huggingface_hub import HfApi
api = HfApi()
api.upload_file(
path_or_fileobj="path/to/your/model.safetensors",
path_in_repo="model.safetensors",
repo_id="your-username/my-awesome-model",
repo_type="model", # 可选:model / dataset / space
)
3.2 上传整个文件夹
python
from huggingface_hub import upload_folder
upload_folder(
folder_path="./my_model_directory",
repo_id="your-username/my-awesome-model",
repo_type="model",
ignore_patterns=["*.tmp", ".git", "__pycache__"], # 忽略不需要的文件
)
3.3 创建仓库并上传(一键搞定)
python
from huggingface_hub import create_repo, upload_folder
# 1. 创建仓库(如果不存在)
create_repo(
repo_id="your-username/my-awesome-model",
repo_type="model",
private=False, # True 为私有仓库
exist_ok=True # 仓库已存在时不报错
)
# 2. 上传文件夹
upload_folder(
folder_path="./my_model",
repo_id="your-username/my-awesome-model",
)
3.4 带进度条的上传
python
from huggingface_hub import upload_file
from tqdm.auto import tqdm
api.upload_file(
path_or_fileobj="big_model.safetensors",
path_in_repo="big_model.safetensors",
repo_id="your-username/my-model",
commit_message="Upload big model with progress",
)
✅ 优点:自动处理大文件、支持断点续传、代码可复现、适合 CI/CD 集成。
4. 方式三:Git + Git LFS 上传(适合大模型)
适合场景:模型文件 > 5GB、习惯 Git 工作流、需要版本控制。
4.1 安装 Git LFS
bash
# macOS
brew install git-lfs
# Ubuntu/Debian
curl -s https://packagecloud.io/install/repositories/github/git-lfs/script.deb.sh | sudo bash
sudo apt-get install git-lfs
# 初始化
git lfs install
4.2 创建仓库并关联
bash
# 在 Hugging Face 上创建空仓库后
git clone https://huggingface.co/your-username/my-model
cd my-model
4.3 追踪大文件
bash
# 追踪所有模型权重文件
git lfs track "*.bin"
git lfs track "*.safetensors"
git lfs track "*.pt"
git lfs track "*.pth"
git lfs track "*.ckpt"
# 这会生成 .gitattributes 文件
git add .gitattributes
4.4 添加文件并推送
bash
# 添加模型文件
git add model.safetensors config.json tokenizer.json README.md
# 提交
git commit -m "Initial model upload"
# 推送到 Hub
git push origin main
💡 小贴士 :Git LFS 在 Hugging Face Hub 上没有存储限制(不像 GitHub 限制 1GB),所以放心上传大模型!
4.5 SSH 方式(更稳定)
如果你遇到 HTTPS 超时,可以配置 SSH:
bash
# 生成 SSH key
ssh-keygen -t ed25519 -C "your@email.com"
# 复制公钥到 Hugging Face Settings → SSH and GPG keys
cat ~/.ssh/id_ed25519.pub
# 测试连接
ssh -T git@hf.co
# 使用 SSH 克隆
git clone git@hf.co:your-username/my-model
5. 方式四:PyTorchModelHubMixin(自定义模型神器)
如果你训练了一个自定义 PyTorch 模型(不是 Transformers 库的标准模型),想让用户像加载 BERT 一样 from_pretrained() 加载你的模型,用这个方式!
5.1 定义模型
python
import torch
import torch.nn as nn
from huggingface_hub import PyTorchModelHubMixin
class MyCustomModel(
nn.Module,
PyTorchModelHubMixin,
repo_url="https://github.com/yourname/repo",
pipeline_tag="text-classification",
license="mit",
):
def __init__(self, num_channels: int, hidden_size: int, num_classes: int):
super().__init__()
self.conv = nn.Conv2d(num_channels, hidden_size, 3)
self.fc = nn.Linear(hidden_size, num_classes)
def forward(self, x):
x = torch.relu(self.conv(x))
x = x.mean(dim=[2, 3]) # Global average pooling
return self.fc(x)
5.2 保存并上传
python
# 实例化模型
config = {"num_channels": 3, "hidden_size": 64, "num_classes": 10}
model = MyCustomModel(**config)
# 保存到本地
model.save_pretrained("my-awesome-model")
# 一键上传到 Hub
model.push_to_hub("your-username/my-awesome-model")
5.3 用户加载模型
python
# 任何人都可以这样加载你的模型!
model = MyCustomModel.from_pretrained("your-username/my-awesome-model")
🎉 自动获得下载统计:使用这种方式上传的模型,会自动统计下载次数,和 Transformers 官方模型一样!
6. 最佳实践与避坑指南
✅ 推荐做法
| 实践 | 说明 |
|---|---|
使用 safetensors 格式 |
比 .bin 更安全、加载更快,Hugging Face 官方推荐 |
| 编写模型卡片 | 上传 README.md,说明模型用途、训练数据、使用示例 |
| 包含配置文件 | 上传 config.json,方便用户了解模型结构 |
| 添加 License | 明确许可证(MIT、Apache-2.0 等) |
使用 .gitignore |
忽略日志、缓存、临时文件 |
📝 模型卡片模板(README.md)
markdown
---
language: zh
license: apache-2.0
library_name: transformers
tags:
- text-classification
- chinese
datasets:
- your-dataset
---
# My Awesome Model
## 模型简介
简要描述你的模型是做什么的。
## 使用方法
```python
from transformers import AutoModel, AutoTokenizer
model = AutoModel.from_pretrained("your-username/my-model")
tokenizer = AutoTokenizer.from_pretrained("your-username/my-model")
训练数据
描述训练数据来源和规模。
性能指标
| 指标 | 数值 |
|---|---|
| Accuracy | 0.95 |
| F1 | 0.94 |
Citation
如果发表了论文,提供 BibTeX。
bash
### ⚠️ 常见问题
**Q1: 上传时报 401/403 错误?**
```bash
# 重新登录
huggingface-cli logout
huggingface-cli login
# 确保 token 有 write 权限
Q2: 大文件上传中断怎么办?
- Python API 会自动断点续传
- Git 方式:检查网络后重新
git push
Q3: 如何上传私有模型?
python
create_repo(repo_id="xxx", private=True)
# 或在 Web 界面创建时勾选 Private
Q4: 模型文件应该包含哪些?
perl
my-model/
├── config.json # 模型配置
├── model.safetensors # 权重文件(推荐)
├── tokenizer.json # 词表
├── tokenizer_config.json
├── special_tokens_map.json
├── vocab.txt # 如有
└── README.md # 模型卡片
🎯 总结
| 方式 | 适合场景 | 难度 | 推荐指数 |
|---|---|---|---|
| Web 界面 | 小文件、快速体验 | ⭐ | ⭐⭐ |
| Python API | 日常开发、自动化 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
| Git + Git LFS | 大模型、版本控制 | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| PyTorchModelHubMixin | 自定义 PyTorch 模型 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
🚀 建议:日常开发优先用 Python API,大模型用 Git LFS,自定义模型用 Mixin。三者也可以组合使用!
希望这篇指南对你有帮助!如果你在上传过程中遇到问题,欢迎在评论区交流 👇
参考链接: