You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未设置push_to_hub=True,如何在Google Colab推送模型checkpoint到Huggingface?

在Google Colab中手动上传训练好的模型到Hugging Face Hub的方法

如果训练时没设置push_to_hub=True,可以用以下两种常用方法手动上传模型:

方法一:使用huggingface_hub库的API上传

这是最便捷的方式,适合大多数场景:

  1. 安装并登录Hugging Face Hub
    先安装依赖库,然后通过交互式登录验证身份:
!pip install huggingface_hub
from huggingface_hub import login
login()  # 执行后会弹出输入框,输入你的Hugging Face访问令牌即可
  1. 加载本地训练好的模型和Tokenizer
    假设你已经将训练后的模型保存到Colab的./trained_model目录下:
from transformers import AutoModel, AutoTokenizer

# 根据你的模型类型替换对应的类,比如AutoModelForSequenceClassification
model = AutoModel.from_pretrained("./trained_model")
tokenizer = AutoTokenizer.from_pretrained("./trained_model")
  1. 推送模型到Hub
    直接调用模型和Tokenizer的push_to_hub方法,指定你的仓库ID(格式为用户名/仓库名):
model.push_to_hub("your-username/your-target-model-repo")
tokenizer.push_to_hub("your-username/your-target-model-repo")

如果想一次性上传整个模型文件夹,也可以用upload_folder方法:

from huggingface_hub import upload_folder

upload_folder(
    folder_path="./trained_model",
    repo_id="your-username/your-target-model-repo",
    repo_type="model"
)

方法二:通过Git命令手动上传

适合熟悉Git操作的用户,步骤如下:

  1. 安装Git LFS并配置Git信息
    Hugging Face Hub依赖Git LFS存储大模型文件,所以先安装并配置:
!apt install git-lfs
!git config --global user.name "Your Full Name"
!git config --global user.email "your-email@example.com"
  1. 克隆目标模型仓库
    如果已经在Hugging Face Hub创建了仓库,直接克隆(替换为你的仓库地址和访问令牌):
!git clone https://your-huggingface-token@huggingface.co/your-username/your-target-model-repo

如果还没创建仓库,也可以先在Hub网页端创建,再执行克隆。

  1. 复制模型文件到仓库目录
    将本地训练好的模型文件复制到克隆的仓库文件夹中:
!cp -r ./trained_model/* ./your-target-model-repo/
  1. 提交并推送代码
    进入仓库目录,执行Git提交和推送:
%cd your-target-model-repo
!git add .
!git commit -m "Upload trained model files"
!git push

注意事项

  • 确保你的Hugging Face访问令牌拥有仓库的写入权限,令牌可以在Hub的个人设置页面生成
  • Colab的临时存储会在会话结束后清空,训练完成后建议先将模型保存到Google Drive或下载到本地,避免丢失
  • 大模型上传时,Git LFS会自动处理大文件,无需手动拆分

内容的提问来源于stack exchange,提问作者user19756157

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:05:06