Sign in

    modelhub

    MoonBit × HuggingFace 生态栈:与 huggingface_hub 兼容的 Hub 客户端、张量推理内核、GPT-2 推理与通用 ONNX 图执行器。

    huggingface
    hub
    llm
    ml
    tensor
    transformers
    onnx
    inference
    download
    cache
    Download zip
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    last month
    Downloads
    20

    #moonkit:MoonBit × HuggingFace 生态栈

    用纯 MoonBit 补齐 HuggingFace 生态的关键基础件,让 MoonBit 程序可以完整地 「拉模型 → 分词 → 跑推理」。仓库包含四个子包,每一层都有与 Python 生态 对照的自动化验证。

    子包定位状态验证方式
    QUHONGYE-gif/modelhubHuggingFace Hub 客户端(下载/缓存/认证/离线/镜像)✅与 huggingface_hub 1.31 缓存树逐文件 parity(本地 mock + 真实 hf-mirror,含 LFS)
    moonkit/nn张量与推理内核(GEMM/激活/归一化/注意力/KV cache)✅numpy golden 逐元素对照
    moonkit/transformersGPT-2 级模型推理(safetensors/前向/生成)✅numpy golden + 真实 tiny-random-gpt2 端到端生成
    moonkit/onnx通用 ONNX 图解释执行器(11 算子)✅numpy golden + 官方 ONNX backend test 子集

    #快速开始

    开发环境隔离在 conda 环境 moonbit 中(工具链 + Python 测试依赖):

    conda activate moonbit moon test --target native # 全部测试(31 个) moon test # wasm 目标(21 个)

    一键体验:

    bash scripts/run_examples.sh # 张量 / ONNX / Hub 三个示例(Hub 用本地 mock) bash scripts/demo_gpt2.sh # 端到端:拉模型 → 分词 → 生成 → 解码(需网络) bash scripts/bench.sh # 基准(matmul / attention / GPT-2 / ONNX) python scripts/parity_test.py # 与 Python huggingface_hub 的 parity 验证

    #各子包用法

    // 1) 拉模型(HF 兼容缓存)
    ///|
    let config = @modelhub.HubConfig::new("https://hf-mirror.com", "/tmp/hf-cache")

    ///|
    let path = @modelhub.hf_hub_download(
    "openai-community/gpt2", "config.json", config,
    )

    ///|
    let snapshot = @modelhub.snapshot_download(
    "sshleifer/tiny-gpt2",
    config,
    None,
    None,
    )

    // 2) 张量与算子

    ///|
    let y = @nn.Tensor::randn([64, 64], 42UL).matmul(
    @nn.Tensor::randn([64, 64], 7UL),
    )

    ///|
    let probs = y.softmax()

    // 3) GPT-2 推理(safetensors 权重 + KV cache 生成)

    ///|
    let model = @transformers.Gpt2Model::load(
    cfg,
    @transformers.parse_safetensors(bytes),
    )

    ///|
    let text_ids = @transformers.Generator::new(model).generate(prompt_ids, 20, 0.0)

    // 4) ONNX 图执行

    ///|
    let graph = @onnx.parse_model(onnx_bytes)

    ///|
    let outputs = @onnx.run_model(graph, inputs)

    详见各子包文档:nn、 transformers、onnx、 modelhub 设计。

    #验证哲学

    这个项目把「可验证」当作第一原则,三层验证都可用脚本复现:

    1. parity:modelhub 在同一个服务端下与 Python huggingface_hub 生成的 缓存树逐文件一致(scripts/parity_test.py,支持本地 mock 与真实端点);
    2. golden:nn / transformers / onnx 的全部算子与语义以 numpy 参考实现 生成期望值、逐元素对照(scripts/gen_*_fixture.py);
    3. 官方一致性:ONNX 侧直接跑官方 backend test 用例 (tests/fixtures/onnx-backend/)。

    #文档索引

    #许可证

    Apache-2.0

    HubError

    pub(all) suberror HubError {
    RevisionNotFound(String)
    EntryNotFound(String)
    GatedRepo(String)
    Offline(String)
    BadStatus(Int, String)
    Parse(String)
    Io(String)
    } derive(Eq,
    Debug
    )

    impl Show for HubError

    HubConfig

    pub struct HubConfig {
    endpoint : String
    cache_dir : String
    revision : String
    subfolder : String
    token : String?
    offline : Bool
    }

    HubConfig::new

    fn HubConfig::new(endpoint : String, cache_dir : String) -> HubConfig

    HubConfig::with_cache_dir

    fn HubConfig::with_cache_dir(self : HubConfig, cache_dir : String) -> HubConfig

    HubConfig::with_endpoint

    fn HubConfig::with_endpoint(self : HubConfig, endpoint : String) -> HubConfig

    HubConfig::with_offline

    fn HubConfig::with_offline(self : HubConfig, offline : Bool) -> HubConfig

    HubConfig::with_revision

    fn HubConfig::with_revision(self : HubConfig, revision : String) -> HubConfig

    HubConfig::with_subfolder

    fn HubConfig::with_subfolder(self : HubConfig, subfolder : String) -> HubConfig

    HubConfig::with_token

    fn HubConfig::with_token(self : HubConfig, token : String) -> HubConfig

    RepoInfo

    pub struct RepoInfo {
    id : String
    sha : String?
    private : Bool
    downloads : Int
    likes : Int
    siblings : Array[String]
    } derive(
    Debug
    )

    blob_dir

    fn blob_dir(cache_root : String, repo_id : String) -> String

    内容寻址存储目录:blobs/。

    copy_stream

    async fn copy_stream(client :
    Client
    , path : String, offset : Int) -> Unit raise HubError

    把 client 的剩余响应体写入 path;offset > 0 时以追加模式续写。 中断时保留已写入的部分并抛 Io。

    dataset_info

    async fn dataset_info(repo_id : String, config : HubConfig) -> RepoInfo raise HubError

    查询数据集仓库元信息。

    default_cache_dir

    fn default_cache_dir() -> String

    默认缓存根目录:HF_HUB_CACHE,否则 ~/.cache/huggingface/hub。

    default_config

    async fn default_config() -> HubConfig

    从环境变量组装默认配置。

    default_endpoint

    fn default_endpoint() -> String

    默认端点:HF_ENDPOINT 环境变量,否则官方地址。

    default_offline

    fn default_offline() -> Bool

    离线模式默认值:HF_HUB_OFFLINE ∈ {1,true,TRUE,yes}。

    dirname

    fn dirname(path : String) -> String

    download_resumable

    async fn download_resumable(url : String, token : String?, cache_root : String, repo_id : String) -> String raise HubError

    下载 url 到 blobs 目录:探测 etag,流式写入 blobs/.incomplete, 支持断点续传(Range),完成后重命名为 blobs/,返回 etag。

    ensure_cache_tag

    async fn ensure_cache_tag(cache_root : String) -> Unit raise HubError

    写入缓存根目录标记文件(内容与 huggingface_hub 一致),幂等。

    ensure_dir

    async fn ensure_dir(path : String) -> Unit raise HubError

    递归创建目录,目录已存在则忽略。

    fetch_revision_info

    async fn fetch_revision_info(endpoint : String, repo_id : String, revision : String, token : String?) -> (String, Array[String]) raise HubError

    请求 revision 信息:commit sha 与文件列表(siblings)。

    file_size

    async fn file_size(path : String) -> Int raise HubError

    get_follow

    async fn get_follow(url : String, headers : Map[
    CaseInsensitiveString
    , String], max_redirects : Int) -> (Int, Map[
    CaseInsensitiveString
    , String], Bytes) raise HubError

    发起 GET 并手动跟随重定向,返回最终状态码、响应头与响应体字节。

    get_stream_follow

    async fn get_stream_follow(url : String, headers : Map[
    CaseInsensitiveString
    , String], max_redirects : Int) -> (Int, String?,
    Client
    ) raise HubError

    与 get_follow 相同,但流式读取响应体:返回状态码、重定向链上首个 linked etag(优先 x-linked-etag,其次 etag)与客户端 reader。

    hf_hub_download

    async fn hf_hub_download(repo_id : String, filename : String, config : HubConfig) -> String raise HubError

    下载 repo 中的单个文件到 HF 兼容缓存,返回快照目录中的本地文件路径。 缓存命中时不做任何网络请求。

    load_default_token

    async fn load_default_token() -> String?

    认证 token 默认值:HF_TOKEN → HUGGING_FACE_HUB_TOKEN → token 文件。

    matches_glob

    fn matches_glob(filename : String, pattern : String) -> Bool

    glob 风格匹配(* / ?),整串匹配。

    model_info

    async fn model_info(repo_id : String, config : HubConfig) -> RepoInfo raise HubError

    查询模型仓库元信息。

    partial_size

    async fn partial_size(path : String) -> Int raise HubError

    path_exists

    async fn path_exists(path : String) -> Bool raise HubError

    read_refs_file

    async fn read_refs_file(path : String) -> String? raise HubError

    refs_path

    fn refs_path(cache_root : String, repo_id : String, revision : String) -> String

    revision -> commit 映射文件:refs/。

    remove_file

    async fn remove_file(path : String) -> Unit raise HubError

    rename_checked

    async fn rename_checked(old : String, new : String) -> Unit raise HubError

    repo_cache_dir

    fn repo_cache_dir(cache_root : String, repo_id : String) -> String

    仓库在缓存中的目录名:models--,斜杠替换为双连字符。

    resolve_sha

    async fn resolve_sha(endpoint : String, repo_id : String, revision : String, cache_dir : String, token : String?, offline : Bool) -> String raise HubError

    解析 revision 为 commit sha:优先读本地 refs 文件(零网络), 否则请求远端 API 并写回 refs。

    snapshot_dir

    fn snapshot_dir(cache_root : String, repo_id : String, commit_sha : String) -> String

    快照目录:snapshots/。

    snapshot_download

    async fn snapshot_download(repo_id : String, config : HubConfig, allow_patterns : Array[String]?, ignore_patterns : Array[String]?) -> String raise HubError

    下载整个模型快照到 HF 兼容缓存,返回快照目录。 离线模式下暂不支持(需要远端 siblings 列表)。
    async fn symlink_checked(target : String, link : String) -> Unit raise HubError

    创建符号链接,底层 IO 错误统一映射为 HubError::Io。

    write_file_checked

    async fn write_file_checked(path : String, content : &
    Data
    ) -> Unit raise HubError

    写文件,底层 IO 错误统一映射为 HubError::Io。