huggingface_hub集成库完整流程:从概念到实现的每一步

【免费下载链接】huggingface_hub The official Python client for the Huggingface Hub. 【免费下载链接】huggingface_hub 项目地址: https://gitcode.com/gh_mirrors/hu/huggingface_hub

huggingface_hub是Hugging Face Hub的官方Python客户端,提供了与机器学习模型库集成的核心功能。本文将详细介绍如何将huggingface_hub集成到你的机器学习框架中,从概念理解到实际实现,帮助开发者轻松实现模型的上传、下载和共享功能。

🌟 集成准备:了解核心概念

在开始集成前,需要理解huggingface_hub的两个核心集成方式:

1.1 灵活的辅助函数方法

通过手动实现push_to_hubfrom_pretrained方法,完全控制文件的上传/下载流程。这种方式适合需要高度定制化的场景,例如FastAI的集成就是采用这种方式实现的[push_to_hub_fastai]和[from_pretrained_fastai]。

1.2 基于类继承的混入方法

利用ModelHubMixin类实现多继承,快速获得完整的Hub交互能力。这种方式通过实现少量私有方法,即可获得丰富的功能支持,如PyTorch的集成[PyTorchModelHubMixin]。

🛠️ 实现步骤:两种集成方案详解

2.1 辅助函数方法实现

2.1.1 从Hub下载模型(from_pretrained)
def from_pretrained(model_id: str) -> MyModelClass:
    # 从Hub下载模型
    cached_model = hf_hub_download(
        repo_id=repo_id,
        filename="model.pkl",
        library_name="fastai",
        library_version=get_fastai_version(),
    )
    
    # 加载模型
    return load_model(cached_model)
2.1.2 上传模型到Hub(push_to_hub)
def push_to_hub(model: MyModelClass, repo_name: str) -> None:
    api = HfApi()
    
    # 创建仓库(如果不存在)并获取repo_id
    repo_id = api.create_repo(repo_name, exist_ok=True)
    
    # 在临时目录中保存所有文件并一次性提交
    with TemporaryDirectory() as tmpdir:
        tmpdir = Path(tmpdir)
        
        # 保存权重
        save_model(model, tmpdir / "model.safetensors")
        
        # 生成模型卡片
        card = generate_model_card(model)
        (tmpdir / "README.md").write_text(card)
        
        # 推送至Hub
        return api.upload_folder(repo_id=repo_id, folder_path=tmpdir)

2.2 类继承混入方法实现

2.2.1 继承ModelHubMixin
from huggingface_hub import ModelHubMixin

class PyTorchModelHubMixin(ModelHubMixin):
    ...
2.2.2 实现_save_pretrained方法
def _save_pretrained(self, save_directory: Path) -> None:
    """将PyTorch模型权重保存到本地目录"""
    save_model_as_safetensor(self.module, str(save_directory / SAFETENSORS_SINGLE_FILE))
2.2.3 实现_from_pretrained方法
@classmethod  # 必须是类方法!
def _from_pretrained(
    cls,
    *,
    model_id: str,
    revision: str,
    cache_dir: str,
    force_download: bool,
    local_files_only: bool,
    token: Union[str, bool, None],
    map_location: str = "cpu",  # 额外参数
    strict: bool = False,  # 额外参数
    **model_kwargs,
):
    """加载PyTorch预训练权重并返回加载的模型"""
    model = cls(**model_kwargs)
    if os.path.isdir(model_id):
        print("从本地目录加载权重")
        model_file = os.path.join(model_id, SAFETENSORS_SINGLE_FILE)
        return cls._load_as_safetensor(model, model_file, map_location, strict)
    
    model_file = hf_hub_download(
        repo_id=model_id,
        filename=SAFETENSORS_SINGLE_FILE,
        revision=revision,
        cache_dir=cache_dir,
        force_download=force_download,
        token=token,
        local_files_only=local_files_only,
    )
    return cls._load_as_safetensor(model, model_file, map_location, strict)

🚀 实际应用:PyTorch模型集成示例

3.1 定义模型类

import torch
import torch.nn as nn
from huggingface_hub import PyTorchModelHubMixin

class MyModel(
    nn.Module,
    PyTorchModelHubMixin,  # 多继承
    library_name="keras-nlp",
    tags=["keras"],
    repo_url="https://github.com/keras-team/keras-nlp",
    docs_url="https://keras.io/keras_nlp/",
):
    def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
        super().__init__()
        self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
        self.linear = nn.Linear(output_size, vocab_size)
    
    def forward(self, x):
        return self.linear(x + self.param)

3.2 模型使用流程

# 1. 创建模型
model = MyModel(hidden_size=128)

# 2. (可选) 保存模型到本地目录
model.save_pretrained("path/to/my-awesome-model")

# 3. 将模型权重推送到Hub
model.push_to_hub("my-awesome-model")

# 4. 从Hub加载模型
model = MyModel.from_pretrained("username/my-awesome-model")

📄 高级功能:模型卡片与配置

4.1 自定义模型卡片

MODEL_CARD_TEMPLATE = """
---
{{ card_data }}
---

这是一个VoiceCraft模型。更多详情,请查看官方Github仓库: https://github.com/jasonppy/VoiceCraft。
本模型采用Attribution-NonCommercial-ShareAlike 4.0 International许可协议。

## 引用

@article{peng2024voicecraft,
  author    = {Peng, Puyuan and Huang, Po-Yao and Li, Daniel and Mohamed, Abdelrahman and Harwath, David},
  title     = {VoiceCraft: Zero-Shot Speech Editing and Text-to-Speech in the Wild},
  journal   = {arXiv},
  year      = {2024},
}
"""

class VoiceCraft(
    nn.Module,
    PyTorchModelHubMixin,
    library_name="voicecraft",
    model_card_template=MODEL_CARD_TEMPLATE,
):
    ...

4.2 配置自定义类型序列化

from argparse import Namespace

class VoiceCraft(
    nn.Module,
    PyTorchModelHubMixin,  # 继承mixin
    coders={
        Namespace : (
            lambda x: vars(x),  # 编码器:如何将Namespace转换为可json化的值
            lambda data: Namespace(**data),  # 解码器:如何从字典重建Namespace
        )
    }
):
    def __init__(self, args: Namespace):  # 为args添加类型注解
        self.pattern = self.args.pattern
        self.hidden_size = self.args.hidden_size
        ...

📊 集成方案对比

集成方式 辅助函数方法 ModelHubMixin方法
用户体验 model = load_from_hub(...)
push_to_hub(model, ...)
model = MyModel.from_pretrained(...)
model.push_to_hub(...)
灵活性 非常灵活,完全控制实现 灵活性较低,需要框架有模型类
维护成本 较高,需手动添加配置和新功能支持 较低,大部分Hub交互由huggingface_hub实现
文档/类型注解 需手动编写 部分由huggingface_hub处理
下载计数 需手动处理 如果类有config属性则默认启用
模型卡片 需手动处理 默认生成,包含library_name、tags等信息

📚 参考资源

通过以上步骤,你可以轻松地将huggingface_hub集成到自己的机器学习框架中,实现模型的无缝上传、下载和共享,为用户提供更好的使用体验。无论是选择灵活的辅助函数方法还是便捷的混入类方法,huggingface_hub都能满足你的集成需求,助力你的项目更好地融入Hugging Face生态系统。

【免费下载链接】huggingface_hub The official Python client for the Huggingface Hub. 【免费下载链接】huggingface_hub 项目地址: https://gitcode.com/gh_mirrors/hu/huggingface_hub

Logo

脑启社区是一个专注类脑智能领域的开发者社区。欢迎加入社区,共建类脑智能生态。社区为开发者提供了丰富的开源类脑工具软件、类脑算法模型及数据集、类脑知识库、类脑技术培训课程以及类脑应用案例等资源。

更多推荐