Transformers documentation

GGUF

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

GGUF

GGUF 是一种用于存储 GGML 推理模型的单文件格式,其中包含模型元数据和张量。它支持多种量化数据类型(参见量化类型表),从而显著节省内存。

加载 GGUF 模型

请安装 kernels,否则在加载时,packed 路径将回退到完整的 dequantization。

pip install kernels

当 Hub 内核 ggml-org/ggml-quantization 可用时,权重将保持打包状态。如果存在该内核,加载器默认使用 MPS,并直接在打包块上执行矩阵乘法。如果该内核不可用,模型将在加载时进行反量化。

from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "unsloth/Qwen3.5-4B-GGUF"
filename = "Qwen3.5-4B-Q4_K_M.gguf"

model = AutoModelForCausalLM.from_pretrained(model_id, gguf_file=filename)
tokenizer = AutoTokenizer.from_pretrained(model_id, gguf_file=filename)

相同的加载方式也适用于 Qwen3.5 MoE。

moe_model_id = "unsloth/Qwen3.5-35B-A3B-GGUF"
moe_filename = "Qwen3.5-35B-A3B-Q4_K_M.gguf"

moe_model = AutoModelForCausalLM.from_pretrained(moe_model_id, gguf_file=moe_filename)
moe_tokenizer = AutoTokenizer.from_pretrained(moe_model_id, gguf_file=moe_filename)

Packed 路径目前支持 Qwen3.5 和 Qwen3.5 MoE。由于在 MPS 上速度更快,Packed 加载会自动使用 float32。如果设置了其他 dtype,加载器会返回警告。其他架构将通过传统加载器处理。

注意力

在 MPS 上,如果已安装内核,加载 GGUF 文件时 ggml-attn 是默认的注意力机制:即 llama.cpp 在 decode 和 prefill 阶段所使用的同一 flash-attention 内核。如果无法获取该内核,模型将保留其原有的注意力实现。传入 attn_implementation(例如 "sdpa")始终具有最高优先级。

您也可以显式地传入它:

model = AutoModelForCausalLM.from_pretrained(
    model_id, gguf_file=filename, attn_implementation="ggml-org/ggml-attn"
)

反量化

Dequantizing 会在加载时解包所有权重,并返回一个普通的稠密模型。当快速压缩路径不适用时,它会作为回退方案。你也可以通过 GgufConfig 显式请求该操作。

import torch

from transformers import AutoModelForCausalLM, GgufConfig

quantization_config = GgufConfig(dequantize=True)
model = AutoModelForCausalLM.from_pretrained(
    model_id, gguf_file=filename, quantization_config=quantization_config, dtype=torch.bfloat16
)

您将获得一个以您传入的dtype为数据类型的常规稠密模型。

除 Qwen3.5 和 Qwen3.5 MoE 之外的架构会通过旧版加载器进行加载,该加载器始终执行反量化。

旧版加载器支持 Llama、Mistral、Qwen2、Qwen2Moe、Phi3、Bloom、Falcon、StableLM、GPT2、Starcoder2 以及更多。

服务

transformers serve 将仓库中的每个 .gguf 文件都作为独立的模型列出。由于一个仓库包含多种量化版本,模型 ID 必须指明要加载哪一个,因此 GGUF 模型的命名为 <repo>:<file>.gguf。请求中也以相同的方式指定该模型。

transformers serve unsloth/Qwen3.5-4B-GGUF:Qwen3.5-4B-Q4_K_M.gguf
Update on GitHub